如何将Counter结果转换为元组列表

时间:2018-10-06 03:00:08

标签: python python-3.x dictionary tuples counter

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

如何从上面获得下面的内容

result = [(apple ,2), (pear, 1)]

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

tuple命令不起作用:

>>> tuple(Counter(example))
('apple', 'pear')

2 个答案:

答案 0 :(得分:1)

您可以在list上致电Counter.items

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(),它返回一个元组列表。

答案 1 :(得分:0)

只需:

Counter(example).items()

不是列表,但是如果需要列表:

list(Counter(example).items())

因为Counter本质上是一个字典,具有与字典相同的功能,所以Counter具有items

只有Counter有一个elementsmost_commonmost_common实际上可以解决这个问题),elements会将Counter转换为{ {1}}对象然后成为列表将是原始列表,但按出现顺序排序。

itertools.chain示例:

most_common

无需转换为列表,它已经是列表,但是它按出现次数排序(意味着最大---到---最小)。

两个输出:

Counter(example).most_common()