简体   繁体   English

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

[英]Access contents of list after applying Counter from collections module

I've applied the Counter function from the collections module to a list. 我已将Collections模块中的Counter函数应用于列表。 After I do this, I'm not exactly clear as to what the contents of the new data structure would be characterised as. 完成此操作后,我不清楚新数据结构的内容将如何表征。 I'm also not sure what the preferred method for accessing the elements is. 我也不确定访问元素的首选方法是什么。

I've done something like: 我做了类似的事情:

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

which returns: 返回:

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

How do I access each element and print out something like: 如何访问每个元素并打印出类似以下内容的内容:

blue - 3
red - 2
yellow - 1

The Counter object is a sub-class of a dictionary. Counter对象是字典的子类。

A Counter is a dict subclass for counting hashable objects. 计数器是用于计算可哈希对象的dict子类。 It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. 它是一个无序集合,其中元素存储为字典键,其计数存储为字典值。

You can access the elements the same way you would another dictionary: 您可以像访问其他字典一样访问元素:

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

If you want to print the keys and values you can do this: 如果要打印键和值,可以执行以下操作:

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

If you want Colors count in descending order you can try like below 如果您希望颜色按降序计数,可以尝试如下操作

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

Output: 输出:

blue 3
red 2
yellow 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM