排序/格式化计数器输出

时间:2019-07-12 14:55:41

标签: python python-3.x counter

我正在尝试按值大小对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

1 个答案:

答案 0 :(得分:3)

您可以使用Running on http://127.0.0.1:8050/ Debugger PIN: 201-392-957 * Serving Flask app "main" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: on Running on http://127.0.0.1:8050/ Debugger PIN: 906-971-228 doc)的most_common()方法:

Counter

打印:

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