c是类Counter的实例化。c.item()是将字典转化成列表,这个列表的每个元素是一个元组。而我们又需要提取元组的第一位。
代码如下:
from collections import Counter
c = Counter('adccbccdf')
print(c)
print(c.items())
word_counts = [x for x in c.items()]
word=[x[0] for x in c.items()]
print(word_counts)
print(word)
结果如下:
Counter({'c': 4, 'd': 2, 'a': 1, 'f': 1, 'b': 1})
dict_items([('a', 1), ('c', 4), ('f', 1), ('b', 1), ('d', 2)])
[('a', 1), ('c', 4), ('f', 1), ('b', 1), ('d', 2)]
['a', 'c', 'f', 'b', 'd']