从集合模块应用Counter后访问列表的内容

时间:2016-01-12 03:08:37

标签: python list collections counter

我已将集合模块中的Counter函数应用于列表。在我这样做之后,我不清楚新数据结构的内容将被表征为什么。我也不确定访问元素的首选方法是什么。

我做过类似的事情:

theList = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
newList = Counter(theList)
print newList

返回:

Counter({'blue': 3, 'red': 2, 'yellow': 1})

如何访问每个元素并打印出如下内容:

blue - 3
red - 2
yellow - 1

2 个答案:

答案 0 :(得分:8)

Counter对象是字典的子类。

  

Counter是用于计算可哈希对象的dict子类。它是一个无序集合,其中元素存储为字典键,它们的计数存储为字典值。

您可以像访问另一个字典一样访问元素:

>>> from collections import Counter
>>> theList = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> newList = Counter(theList)
>>> newList['blue']
3

如果要打印键和值,可以执行以下操作:

>>> for k,v in newList.items():
...     print(k,v)
...
blue 3
yellow 1
red 2

答案 1 :(得分:0)

如果您希望颜色按降序计数,可以尝试如下操作

from collections import OrderedDict
theList = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
newList = Counter(theList)
sorted_dict = OrderedDict(sorted(newList.items(), key = lambda kv : kv[1], reverse=True))
for color in sorted_dict: 
    print (color, sorted_dict[color]) 

输出:

blue 3
red 2
yellow 1