用键在python中排序计数器

cor*_*vid 25 python dictionary python-2.7

我有一个看起来有点像这样的柜台:

Counter: {('A': 10), ('C':5), ('H':4)}
Run Code Online (Sandbox Code Playgroud)

我想按字母顺序对键进行排序,而不是按字母顺序排序 counter.most_common()

有没有办法实现这个目标?

fal*_*tru 47

只需使用已排序:

>>> from collections import Counter
>>> counter = Counter({'A': 10, 'C': 5, 'H': 7})
>>> counter.most_common()
[('A', 10), ('H', 7), ('C', 5)]
>>> sorted(counter.items())
[('A', 10), ('C', 5), ('H', 7)]
Run Code Online (Sandbox Code Playgroud)

  • 注意,这会将 Counter 转换为列表 (3认同)

Rom*_*kar 9

>>> from operator import itemgetter
>>> from collections import Counter
>>> c = Counter({'A': 10, 'C':5, 'H':4})
>>> sorted(c.items(), key=itemgetter(0))
[('A', 10), ('C', 5), ('H', 4)]
Run Code Online (Sandbox Code Playgroud)

  • 但是,itemgetter对于对元组列表或列表列表进行排序很有用,但在dict上它是无用的,有条理的(c)等同于sorted(c.keys()) (2认同)