counting element occurrences in nested lists

前端 未结 3 1457
悲&欢浪女
悲&欢浪女 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:58

    from collections import Counter
    from itertools import chain
    
    counts = Counter(chain.from_iterable(my_list))
    

    or generate a new list and use count:

    new_list = list(chain.from_iterable(my_list))
    print new_list.count(whatever)
    

    If you wanted how many times 'a' is the first, then something like:

    sum(1 for el in my_list if el[0] is a) # or == a if object identity is not required
    

提交回复
热议问题