counting element occurrences in nested lists

前端 未结 3 1436
悲&欢浪女
悲&欢浪女 2021-01-13 16:58

This is probably quite a straightforward question, but I can\'t find an answer elsewhere so I\'ll ask. What is the best way to find the number of times an element appears in

3条回答
  •  时光说笑
    2021-01-13 17:47

    >>> from collections import defaultdict, Counter
    >>> my_list = [['a', 'b', 'c', 'd'], ['a', 'b', 'z', 'd'], ['a', 'c', 'f', 'e'], ['d', 'w', 'f', 'a']]
    >>> pos_count = defaultdict(Counter)
    >>> for sublist in my_list:
            for i, c in enumerate(sublist):
                pos_count[c][i] += 1
    
    
    >>> pos_count['a'][0]
    3
    >>> pos_count['b'][1]
    2
    

提交回复
热议问题