从集合模块应用计数器后访问列表的内容 [英] Access contents of list after applying Counter from collections module

查看:52
本文介绍了从集合模块应用计数器后访问列表的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将collections模块中的Counter函数应用于列表.完成此操作后,我不清楚新数据结构的内容将如何表征.我也不确定访问元素的首选方法是什么.

I've applied the Counter function from the collections module to a list. 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

返回:

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

我如何访问每个元素并打印出类似以下内容的内容:

How do I access each element and print out something like:

blue - 3
red - 2
yellow - 1

推荐答案

Counter 对象是字典的子类.

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

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.

您可以像访问另一本词典一样访问元素:

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

这篇关于从集合模块应用计数器后访问列表的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆