2013-07-18 38 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"])