与清单相反

use*_*700 9 python counter list

我有一个这样的计数器:

counter = Counter(['a','a','b','b','b','c'])
Run Code Online (Sandbox Code Playgroud)

这给出了这个对象:

Counter({'b': 3, 'a': 2, 'c': 1})
Run Code Online (Sandbox Code Playgroud)

从中我想创建一个列表,例如:

list[0] = 'b'
list[1] = 'a'
list[2] = 'c'
Run Code Online (Sandbox Code Playgroud)

有什么想法可以以最简单和最快的方式做到这一点吗?谢谢

fal*_*tru 9

您可以使用collections.Counter.most_common(它返回一个包含 n 个最常见元素及其从最常见到最少的计数的列表):

>>> counter.most_common()
[('b', 3), ('a', 2), ('c', 1)]

>>> [key for key, _ in counter.most_common()]
['b', 'a', 'c']
Run Code Online (Sandbox Code Playgroud)


sha*_*k3r 5

falsetru 所说的最简单(IMO)方法

sorted(counter, key=counter.get, reverse=True)
Run Code Online (Sandbox Code Playgroud)

上面的代码将dict根据键 ( .get()) 的值对计数器进行排序并返回相反的list