<分区>
example = ['apple', 'pear', 'apple']
如何从上面得到下面的内容
result = [(apple ,2), (pear, 1)]
我只知道如何使用Counter
,但我不知道如何将结果变成上面的格式。
元组命令不起作用:
>>> tuple(Counter(example))
('apple', 'pear')
<分区>
example = ['apple', 'pear', 'apple']
如何从上面得到下面的内容
result = [(apple ,2), (pear, 1)]
我只知道如何使用Counter
,但我不知道如何将结果变成上面的格式。
元组命令不起作用:
>>> tuple(Counter(example))
('apple', 'pear')
最佳答案
您可以在 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()
,它会返回一个元组列表。
关于python - 如何将计数器结果转换为元组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52675339/