Sorting/formatting 计数器输出

Sorting/formatting Counter output

我正在尝试按值大小对 Counter 的输出进行排序。当前代码以看似随机的顺序输出它们

from collections import Counter
query_list = list()

for line in contents:
      if not line.startswith("#"):
            columns = line.split()
            query = str(columns[9])
            query_list.append(query)

queries = Counter(query_list)
for key, value in queries.items():
    print(value,key)

当前输出如下所示:

36 key_a
24 key_b
18 key_c
97 key_d
99 key_f

理想情况下,输出应按从大到小的顺序排序,如下所示:

99 key_f
97 key_d
36 key_a
24 key_b
18 key_c

使用 sorted 会如您所料出现类型错误

---> 12     print(sorted(value,key))
     13 
     14 

TypeError: sorted expected 1 arguments, got 2

您可以使用 Countermost_common() 方法 (doc):

from collections import Counter

values = {'key_a': 36,
'key_b': 24,
'key_c': 18,
'key_d': 97,
'key_f': 99}

c = Counter(values)

for key, count in c.most_common():
    print(count, key)

打印:

99 key_f
97 key_d
36 key_a
24 key_b
18 key_c

编辑:如果你想使用 sorted():

from operator import itemgetter

for key, count in sorted(c.items(), key=itemgetter(1), reverse=True):
    print(count, key)