[英]Access contents of list after applying Counter from collections module
我已將Collections模塊中的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
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
如果您希望顏色按降序計數,可以嘗試如下操作
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.