2013-07-13 59 views
2

如何創建一個列表,其中包含元素在多個列表中出現的次數。比如我有這些列表:計算在Python中包含元素的列表數量

list1 = ['apples','oranges','grape'] 
list2 = ['oranges, 'oranges', 'pear'] 
list3 = ['strawberries','bananas','apples'] 
list4 = [list1,list2,list3] 

我要計算包含每個元素的文檔的數量,並把它在字典中,所以對於蘋果^和橘子,我得到這樣的:

term['apples'] = 2 
term['oranges'] = 2 #not 3 
+0

'term ['apples' ]'暗示使用字典。 – dansalmo

+3

你需要計算'桔子'的數量? 2或3? – shx2

+0

2 ...文件數量:) – user2578185

回答

0
>>> [el for lst in [set(L) for L in list4] for el in lst].count('apples') 
2 
>>> [el for lst in [set(L) for L in list4] for el in lst].count('oranges') 
2 

:或者你可以做到這一點沒有itertools詞典中,可以使用詞典理解來創建來自展平集合列表的直方圖:

>>> list4sets = [set(L) for L in list4] 
>>> list4flat = [el for lst in list4sets for el in lst] 
>>> term = {el: list4flat.count(el) for el in list4flat} 
>>> term['apples'] 
2 
>>> term['oranges'] 
2 
+0

不是'el'的列表嗎?你怎麼能把它用作字典中的關鍵字? – shx2

+0

請解釋你的答案不僅僅是代碼。 – Sergio

+0

我添加的代碼應該是自我記錄。 – dansalmo

0

使用collections.Counter

from collections import Counter 
terms = Counter(x for lst in list4 for x in lst) 
terms 
=> Counter({'oranges': 3, 'apples': 2, 'grape': 1, 'bananas': 1, 'pear': 1, 'strawberries': 1}) 
terms['apples'] 
=> 2 

由於@Stuart指出的那樣,你也可以使用chain.from_iterable,以避免產生表達尷尬的前瞻性雙迴路(即for lst in list4 for x in lst)。

編輯:另一個很酷的技巧是採取Counter S(由this著名的回答啓發)的總和,如:

sum((Counter(lst) for lst in list4), Counter())

+1

我不認爲list4是被包括在內的。 – hetepeperfan

+1

謝謝,但問題是,我想獲得這個詞出現在列表的數量,例如,如果一個列表有5次,它仍然應該算作一個計數... terms ['apple']給出的數字在所有文件中出現此術語,而不是具有蘋果 – user2578185

+0

桔子的文件數應爲2. – dansalmo

0
print (list1 + list2 + list3).count('apples') 

,或者如果你把所有的名單已經在編譯list4,你可以使用itertools.chain作爲一個快速的方法將它們連接:

from itertools import chain 
print list(chain.from_iterable(list4)).count('apples') 

ED IT:如果你想在最終結構爲

print sum(list4, []).count('apples') 

,並可以很容易地複製collections.Counter如果由於某種原因,你想......

all_lists = sum(list4, []) 
print dict((k, all_lists.count(k)) for k in set(all_lists)) 
相關問題