如何将计数器结果转换为元组列表

5
example = ['apple', 'pear', 'apple']

如何从上面的内容中获取以下内容
result = [(apple ,2), (pear, 1)]

我只知道如何使用Counter,但我不确定如何将结果转换为上述格式。

tuple命令无法正常工作:

>>> tuple(Counter(example))
('apple', 'pear')
2个回答

6
您可以在 Counter.items 上调用 list:
from collections import Counter

result = list(Counter(example).items())

[('apple', 2), ('pear', 1)]

dict.items提供了一个键值对的可迭代对象。作为dict的子类,这同样适用于Counter。在可迭代对象上调用list将会返回一个元组列表。

以上内容在Python 3.6+中按插入顺序排列。要按计数降序排列,请使用Counter(example).most_common(),它返回一个元组列表。


3
要按计数排序结果(作为单个调用),可以使用 Counter(example).most_common() ,它将所有工作都完成为单个调用。 - ShadowRanger

1

只需要这样做:

Counter(example).items()

这不是一个列表,但如果需要一个列表:

list(Counter(example).items())

因为Counter基本上是一个字典,具有与字典相等的功能,所以Counteritems,唯一的区别是Counter有一个elementsmost_common(实际上可以解决这个问题),elementsCounter转换为itertools.chain对象,然后将其转换为列表,这将是原始列表,但按出现顺序排序。most_common示例:
Counter(example).most_common()

不需要将列表转换,因为它已经是一个列表,但它按出现次数排序(意思是从最多到最少)。
两个输出:
[('apple', 2), ('pear', 1)]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接