【问题标题】:Sorting/formatting Counter output排序/格式化计数器输出
【发布时间】:2019-07-12 14:55:41
【问题描述】:

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

【问题讨论】:

    标签: python python-3.x counter


    【解决方案1】:

    可以使用Counter(doc)的most_common()方法:

    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)
    

    【讨论】:

      猜你喜欢
      • 2014-06-07
      • 1970-01-01
      • 2010-12-23
      • 1970-01-01
      • 1970-01-01
      • 2016-12-19
      • 1970-01-01
      • 2011-10-31
      相关资源
      最近更新 更多