2013-07-18 37 views
5

我如何計算用嵌套列表創建的多維數組中某些值的出現次數?作中,尋找以下列表「foobar的」時:python .count多維數組(列表清單)

list = [['foobar', 'a', 'b'], ['x', 'c'], ['y', 'd', 'e', 'foobar'], ['z', 'f']] 

它應該返回2

(是的,我知道,我可以寫一個循環,只是通過它的所有搜索,但我不喜歡這種解決方案,因爲它是相當耗費時間,(在運行時編寫和))

.Count之間也許?

回答

9
>>> list = [['foobar', 'a', 'b'], ['x', 'c'], ['y', 'd', 'e', 'foobar'], ['z', 'f']] 
>>> sum(x.count('foobar') for x in list) 
2 
0
>> from collections import Counter 
>> counted = Counter([item for sublist in my_list for item in sublist]) 
>> counted.get('foobar', 'not found!') 
>> 2 
#or if not found in your counter 
>> 'not found!' 

這使用子列表的平坦化,然後使用collections模塊和Counter 以產生字的計數。

2

首先join the lists together using itertools,那麼僅計算使用Collections module每次出現:

import itertools 
from collections import Counter 

some_list = [['foobar', 'a', 'b'], ['x', 'c'], ['y', 'd', 'e', 'foobar'], ['z', 'f']] 
totals = Counter(i for i in list(itertools.chain.from_iterable(some_list))) 
print(totals["foobar"])