在 Python 3.6+ 上,dict 现在将保持插入顺序。
所以你可以这样做:
words = ["oranges", "apples", "apples", "bananas", "kiwis", "kiwis", "apples"]
counter={}
for w in words: counter[w]=counter.get(w, 0)+1
>>> counter
{'oranges': 1, 'apples': 3, 'bananas': 1, 'kiwis': 2}
不幸的是,Python 3.6 和 3.7 中的 Counter 不显示它所维护的插入顺序;相反,__repr__sorts the return 从最常见到最不常见。
但是您可以使用相同的 OrderedDict recipe 但只需使用 Python 3.6+ dict 代替:
from collections import Counter
class OrderedCounter(Counter, dict):
'Counter that remembers the order elements are first encountered'
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, dict(self))
def __reduce__(self):
return self.__class__, (dict(self),)
>>> OrderedCounter(words)
OrderedCounter({'oranges': 1, 'apples': 3, 'bananas': 1, 'kiwis': 2})
或者,由于 Counter 是 dict 的子类,它在 Python 3.6+ 中保持顺序,因此您可以通过在柜台上调用 .items() 或将柜台转回 dict 来避免使用 Counter 的 __repr__ :
>>> c=Counter(words)
该计数器的此演示文稿按最常见元素排序到最少,并使用 Counters __repr__ 方法:
>>> c
Counter({'apples': 3, 'kiwis': 2, 'oranges': 1, 'bananas': 1})
遇到此演示文稿,或插入订单:
>>> c.items()
dict_items([('oranges', 1), ('apples', 3), ('bananas', 1), ('kiwis', 2)])
或者,
>>> dict(c)
{'oranges': 1, 'apples': 3, 'bananas': 1, 'kiwis': 2}