【问题标题】:sorting a counter in python by keys按键对python中的计数器进行排序
【发布时间】:2013-07-29 15:25:59
【问题描述】:

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

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

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

有什么办法可以做到吗?

【问题讨论】:

标签: python python-2.7 dictionary


【解决方案1】:

只需使用sorted:

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

【讨论】:

【解决方案2】:
>>> 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)]

【讨论】:

  • 这行得通,但是,itemgetter 对于对元组列表或列表列表进行排序很有用,但在 dict 上它是无用的, sorted(c) 相当于 sorted(c.keys() )
【解决方案3】:

在 Python 3 中,可以使用 collections.Counter 的most_common 函数:

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

这使用了 collections.Counter 中可用的 most_common 函数,它允许您查找 n 最常用键的键和计数。

【讨论】:

  • 这根本不能回答问题。我得到[('c', 3), ('d', 2), ('a', 1), ('b', 1)],它没有按字母顺序对键进行排序。
  • OP显然知道most_common,问题中提到了。
【解决方案4】:

按排序顺序获取值作为列表

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

【讨论】:

    【解决方案5】:
    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]))
    

    【讨论】:

      猜你喜欢
      • 2014-01-23
      • 2018-08-01
      • 2023-01-22
      • 1970-01-01
      • 2021-11-21
      • 2014-04-11
      • 1970-01-01
      • 2017-12-05
      • 1970-01-01
      相关资源
      最近更新 更多