python .count for multidimensional arrays (list of lists)

后端 未结 3 1423
一整个雨季
一整个雨季 2020-12-17 16:52

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:

相关标签:
3条回答
  • 2020-12-17 17:00

    First join the lists together using itertools, then just count each occurrence using the 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"])
    
    0 讨论(0)
  • 2020-12-17 17:05
    >> 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.

    0 讨论(0)
  • 2020-12-17 17:22
    >>> list = [['foobar', 'a', 'b'], ['x', 'c'], ['y', 'd', 'e', 'foobar'], ['z', 'f']]
    >>> sum(x.count('foobar') for x in list)
    2
    
    0 讨论(0)
提交回复
热议问题