example = ['apple', 'pear', 'apple']
如何从上面的内容中获取以下内容
result = [(apple ,2), (pear, 1)]
我只知道如何使用Counter
,但我不确定如何将结果转换为上述格式。
tuple
命令无法正常工作:
>>> tuple(Counter(example))
('apple', 'pear')
example = ['apple', 'pear', 'apple']
result = [(apple ,2), (pear, 1)]
我只知道如何使用Counter
,但我不确定如何将结果转换为上述格式。
tuple
命令无法正常工作:
>>> tuple(Counter(example))
('apple', 'pear')
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()
,它返回一个元组列表。
只需要这样做:
Counter(example).items()
这不是一个列表,但如果需要一个列表:
list(Counter(example).items())
Counter
基本上是一个字典,具有与字典相等的功能,所以Counter
有items
,唯一的区别是Counter
有一个elements
和most_common
(实际上可以解决这个问题),elements
将Counter
转换为itertools.chain
对象,然后将其转换为列表,这将是原始列表,但按出现顺序排序。most_common
示例:Counter(example).most_common()
[('apple', 2), ('pear', 1)]
Counter(example).most_common()
,它将所有工作都完成为单个调用。 - ShadowRanger