example = ['apple', 'pear', 'apple']
如何从上面获得下面的内容
result = [(apple ,2), (pear, 1)]
我只知道如何使用Counter
,但不确定如何将结果转换为上面的格式。
tuple命令不起作用:
>>> tuple(Counter(example))
('apple', 'pear')
答案 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
有一个elements
和most_common
(most_common
实际上可以解决这个问题),elements
会将Counter
转换为{ {1}}对象然后成为列表将是原始列表,但按出现顺序排序。
itertools.chain
示例:
most_common
无需转换为列表,它已经是列表,但是它按出现次数排序(意味着最大---到---最小)。
两个输出:
Counter(example).most_common()