Vic*_*ell 5 python collections counter list
我已经将collections函数中的Counter函数应用到列表中.在我这样做之后,我不清楚新数据结构的内容将被表征为什么.我也不确定访问元素的首选方法是什么.
我做过类似的事情:
theList = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
newList = Counter(theList)
print newList
Run Code Online (Sandbox Code Playgroud)
返回:
Counter({'blue': 3, 'red': 2, 'yellow': 1})
Run Code Online (Sandbox Code Playgroud)
如何访问每个元素并打印出如下内容:
blue - 3
red - 2
yellow - 1
Run Code Online (Sandbox Code Playgroud)
该计数器对象是一个子类的字典中.
Counter是用于计算可哈希对象的dict子类.它是一个无序集合,其中元素存储为字典键,其计数存储为字典值.
您可以像访问另一个字典一样访问元素:
>>> from collections import Counter
>>> theList = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> newList = Counter(theList)
>>> newList['blue']
3
Run Code Online (Sandbox Code Playgroud)
如果要打印键和值,可以执行以下操作:
>>> for k,v in newList.items():
... print(k,v)
...
blue 3
yellow 1
red 2
Run Code Online (Sandbox Code Playgroud)