在Python中按键对计数器进行排序

问题描述 投票:0回答:6

我有一个看起来有点像这样的计数器:

Counter: {('A': 10), ('C':5), ('H':4)}

我想专门按字母顺序对键进行排序,而不是按

counter.most_common()

有什么办法可以实现这个目标吗?

python python-2.7 dictionary
6个回答
80
投票

只需使用已排序

>>> 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)]

14
投票
>>> 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)]

4
投票
sorted(counter.items(),key = lambda i: i[0])

例如:

arr = [2,3,1,3,2,4,6,7,9,2,19]
c = collections.Counter(arr)
sorted(c.items(),key = lambda i: i[0])

外: [(1, 1), (2, 3), (3, 2), (4, 1), (6, 1), (7, 1), (9, 1), (19, 1)] 如果你想获得字典格式,只需

dict(sorted(c.items(),key = lambda i: i[0]))

2
投票

获取按排序顺序列出的值

array              = [1, 2, 3, 4, 5]
counter            = collections.Counter(array)
sorted_occurrences = list(dict(sorted(counter.items())).values())

0
投票

在Python 3中,可以使用集合的most_common函数。计数器:

x = ['a', 'b', 'c', 'c', 'c', 'd', 'd']
counts = collections.Counter(x)
counts.most_common(len(counts))

这使用了集合中可用的most_common函数。Counter,它允许您查找

n
最常用键的键和计数。


0
投票

请参考我下面的评论

# input data
counter = Counter({'A': 10, 'C': 5, 'H': 7})
# Sorting the Counter by keys
sorted_counter = sorted(counter.items())
# change it back into a counter
result_counter = Counter(sorted_counter)

结果应该是这样的:

Counter({'A': 10, 'C': 5, 'H': 7})
© www.soinside.com 2019 - 2024. All rights reserved.