从集合模块应用计数器后访问列表的内容

Access contents of list after applying Counter from collections module

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

我做过类似的事情:

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

哪个returns:

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

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

blue - 3
red - 2
yellow - 1

Counter 对象是字典的 sub-class。

A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values.

您可以像访问其他字典一样访问元素:

>>> 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

如果你想按降序排列颜色,你可以像下面这样尝试

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