How would I count the number of occurrences of some value in a multidimensional array made with nested lists? as in, when looking for 'foobar' in the following list:
如何计算使用嵌套列表创建的多维数组中某些值的出现次数?在以下列表中寻找'foobar'时:
list = [['foobar', 'a', 'b'], ['x', 'c'], ['y', 'd', 'e', 'foobar'], ['z', 'f']]
it should return 2
.
它应该返回2。
(yes I am aware that I could write a loop that just searches through all of it, but I dislike that solution as it is rather time-consuming, (to write and during runtime))
(是的,我知道我可以编写一个只搜索所有内容的循环,但我不喜欢这个解决方案,因为它相当耗时,(写入和运行时))
.count maybe?
3 个解决方案
#1
8
>>> list = [['foobar', 'a', 'b'], ['x', 'c'], ['y', 'd', 'e', 'foobar'], ['z', 'f']]
>>> sum(x.count('foobar') for x in list)
2
#2
3
First join the lists together using itertools
, then just count each occurrence using the Collections
module:
首先使用itertools将列表连接在一起,然后使用Collections模块计算每个事件:
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"])
#3
1
>> 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!'
This uses flattening of sublists and then using the collections module and Counter to produce the counts of words.
这使用了子列表的展平,然后使用集合模块和计数器来生成单词计数。
#1
8
>>> list = [['foobar', 'a', 'b'], ['x', 'c'], ['y', 'd', 'e', 'foobar'], ['z', 'f']]
>>> sum(x.count('foobar') for x in list)
2
#2
3
First join the lists together using itertools
, then just count each occurrence using the Collections
module:
首先使用itertools将列表连接在一起,然后使用Collections模块计算每个事件:
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"])
#3
1
>> 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!'
This uses flattening of sublists and then using the collections module and Counter to produce the counts of words.
这使用了子列表的展平,然后使用集合模块和计数器来生成单词计数。