2010-08-16 76 views
96

我是新來的Python和我有一個簡單的問題,說我有一個項目列表:的Python:使用字典來算列表中的項目

['apple','red','apple','red','red','pear'] 

請告訴我simpliest方式來添加將項目列入詞典並計算項目在列表中出現的次數。所以

的名單上面,我想輸出是:

{'apple': 2, 'red': 3, 'pear': 1} 
+1

,你可以在這裏得到啓示:HTTP ://stackoverflow.com/questions/2870466/python-histogram-one-liner – mykhal 2010-08-16 19:23:41

+0

http://stackoverflow.com/questions/13242103/how-to-compute-letter-frequency-in-a-string-using-pythons -build-in-map-and-reduc – 2015-08-16 08:47:12

+0

有沒有人注意到輸出的順序?這是不相干的嗎? – 2016-06-18 18:50:33

回答

46
>>> L = ['apple','red','apple','red','red','pear'] 
>>> from collections import defaultdict 
>>> d = defaultdict(int) 
>>> for i in L: 
... d[i] += 1 
>>> d 
defaultdict(<type 'int'>, {'pear': 1, 'apple': 2, 'red': 3}) 
+2

可能是最快和最雜亂的方法。 – 2010-08-16 19:28:56

3
L = ['apple','red','apple','red','red','pear'] 
d = {} 
[d.__setitem__(item,1+d.get(item,0)) for item in L] 
print d 

給人{'pear': 1, 'apple': 2, 'red': 3}

170

在2.7和3.1有特殊Counter字典用於這一目的。

>>> from collections import Counter 
>>> Counter(['apple','red','apple','red','red','pear']) 
Counter({'red': 3, 'apple': 2, 'pear': 1}) 
+11

Yuck;已經足夠的Python庫中的狹義用途了。 – 2010-08-16 20:27:21

+2

圭多有一個時間機器官方的線,或相當長久的笑話。 – 2010-08-17 00:04:56

+8

@Glenn Maynard計數器只是一個** multiset **的實現,它不是一個不常見的數據結構國際海事組織。事實上,C++在STL中有一個名爲'std :: multiset'(也是'std :: tr1 :: unordered_multiset')的實現,所以Guido並不孤單。 – awesomo 2011-10-18 03:07:34

11

我一直認爲對於一個微不足道的任務,我不想導入任何東西。但我可能是錯誤的,取決於collections.Counter是否更快或不。

items = "Whats the simpliest way to add the list items to a dictionary " 

stats = {} 
for i in items: 
    if i in stats: 
     stats[i] += 1 
    else: 
     stats[i] = 1 

# bonus 
for i in sorted(stats, key=stats.get): 
    print("%d×'%s'" % (stats[i], i)) 

我想這可能是最好使用count(),因爲它只會走在迭代一次,而指望可以搜索在每次迭代的整個事情。我使用這種方法來解析許多兆字節的統計數據,並且總是相當快速。

+1

您的答案值得更多因爲它很簡單,我一直在爲此苦苦掙扎,一些其他用戶的愚蠢暗示會導入新的庫等。 – ntk4 2016-09-23 05:56:17

92

我喜歡:

counts = dict() 
for i in items: 
    counts[i] = counts.get(i, 0) + 1 

不用彷徨讓你如果鍵不存在,指定一個默認值。

+6

對於那些新的python。這個答案在時間複雜性方面更好。 – curiousMonkey 2016-04-18 05:07:45

+0

這個答案即使在浮點數的列表中也適用,其中一些數字可能爲'0' – SherylHohman 2017-05-03 05:12:53

6

如何:

src = [ 'one', 'two', 'three', 'two', 'three', 'three' ] 
result_dict = dict([ (i, src.count(i)) for i in set(src) ]) 

這導致

{ '一':1, '三化':3, '兩節':2}

+7

注意這是由於對'src.count()的'n'調用引起的'O(n^2)'。 – dimo414 2014-02-17 20:22:03

23

只需使用列表屬性計數\

i = ['apple','red','apple','red','red','pear'] 
d = {x:i.count(x) for x in i} 
print d 

輸出:{ '梨':1, '蘋果':2, '紅色':3}

+2

雖然它起作用,但這似乎效率不高。 – Ouroborus 2017-09-27 17:41:18

+0

你可以詳細說明嗎? – 2017-11-28 08:59:36

+0

你正在對數組應用'count'多次有數組項目。你的解決方案是'O(n^2)',更好的解決方案是'O(n)'。請參閱[riviera的回答](https://stackoverflow.com/a/9604768/367865)上的評論與[mmdreg的回答](https://stackoverflow.com/a/6582852/367865)上的評論。 – Ouroborus 2017-11-29 09:50:05