son*_*089 5 python counter dictionary tuples python-3.x
example = ['apple', 'pear', 'apple']
Run Code Online (Sandbox Code Playgroud)
我怎样才能从上面得到下面的内容
result = [(apple ,2), (pear, 1)]
Run Code Online (Sandbox Code Playgroud)
我只知道如何使用Counter,但我不知道如何将结果转换为上面的格式。
元组命令不起作用:
>>> tuple(Counter(example))
('apple', 'pear')
Run Code Online (Sandbox Code Playgroud)
您可以list致电Counter.items:
from collections import Counter
result = list(Counter(example).items())
[('apple', 2), ('pear', 1)]
Run Code Online (Sandbox Code Playgroud)
dict.items给出一个可迭代的键、值对。作为 的子类dict,这对于 来说也是如此Counter。因此,调用listiterable 将为您提供一个元组列表。
上面给出了在 Python 3.6+ 中排序的项目插入。要按计数降序排序,请使用Counter(example).most_common(),它返回元组列表。