[英]dict comprehension with unique keys out of list
我不經常使用列表推導,但是我想知道下面的行是否可以是一個直線(是的代碼已經很小,但是我很好奇):
lst = ['hi', 'hello', 'bob', 'hello', 'bob', 'hello']
for index in lst:
data[index] = data.get(index,0) + 1
數據應為:{'hi':1,'hello':3,'bob':2}
的東西:
d = {...對於第一個索引} ????
我已經嘗試了一些理解,但沒有用:
d = { index:key for index in lst if index in d: key = key + 1 else key = 1 }
感謝在廣告中。
計數器是用於計算可哈希對象的dict子類。 它是一個無序集合,其中元素存儲為字典鍵,其計數存儲為字典值。 計數可以是任何整數值,包括零或負計數。 Counter類類似於其他語言的包或多集。
import collections
l = ['hi', 'hello', 'bob', 'hello', 'bob', 'hello']
c = collections.Counter(l)
assert c['hello'] == 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.