欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python模塊簡介之有序字典(OrderedDict)

 更新時間:2016年12月01日 08:35:28   作者:linuxidc  
字典是Python開發(fā)中很常用的一種數(shù)據(jù)結(jié)構(gòu),但dict有個缺陷(其實(shí)也不算缺陷),迭代時并不是按照元素添加的順序進(jìn)行,可能在某些場景下,不能滿足我們的要求。

有序字典-OrderedDict簡介

示例

有序字典和通常字典類似,只是它可以記錄元素插入其中的順序,而一般字典是會以任意的順序迭代的。參見下面的例子:

import collections

print 'Regular dictionary:'
d = {}
d['a'] = 'A'
d['b'] = 'B'
d['c'] = 'C'
d['d'] = 'D'
d['e'] = 'E'

for k, v in d.items():
  print k, v

print '\nOrderedDict:'
d = collections.OrderedDict()
d['a'] = 'A'
d['b'] = 'B'
d['c'] = 'C'
d['d'] = 'D'
d['e'] = 'E'

for k, v in d.items():
  print k, v

運(yùn)行結(jié)果如下:

-> python test7.py
Regular dictionary:
a A
c C
b B
e E
d D

OrderedDict:
a A
b B
c C
d D
e E

可以看到通常字典不是以插入順序遍歷的。

相等性

判斷兩個有序字段是否相等(==)需要考慮元素插入的順序是否相等

import collections

print 'dict    :',
d1 = {}
d1['a'] = 'A'
d1['b'] = 'B'
d1['c'] = 'C'
d1['d'] = 'D'
d1['e'] = 'E'

d2 = {}
d2['e'] = 'E'
d2['d'] = 'D'
d2['c'] = 'C'
d2['b'] = 'B'
d2['a'] = 'A'

print d1 == d2

print 'OrderedDict:',

d1 = collections.OrderedDict()
d1['a'] = 'A'
d1['b'] = 'B'
d1['c'] = 'C'
d1['d'] = 'D'
d1['e'] = 'E'

d2 = collections.OrderedDict()
d2['e'] = 'E'
d2['d'] = 'D'
d2['c'] = 'C'
d2['b'] = 'B'
d2['a'] = 'A'

print d1 == d2

運(yùn)行結(jié)果如下:

-> python test7.py
dict    : True
OrderedDict: False

而當(dāng)判斷一個有序字典和其它普通字典是否相等只需判斷內(nèi)容是否相等。

注意

OrderedDict 的構(gòu)造器或者 update() 方法雖然接受關(guān)鍵字參數(shù),但因?yàn)閜ython的函數(shù)調(diào)用會使用無序的字典來傳遞參數(shù),所以關(guān)鍵字參數(shù)的順序會丟失,所以創(chuàng)造出來的有序字典不能保證其順序。

參考資料

https://docs.python.org/2/library/collections.html#collections.OrderedDict
https://pymotw.com/2/collections/ordereddict.html

相關(guān)文章

最新評論