Count the number of lists containing specific element in a nested list

后端 未结 2 1826
谎友^
谎友^ 2021-01-26 07:19

I have a list, for example:

res = [[\'a\', \'b\', \'a\'], [\'a\', \'b\', \'c\'], [\'a\']]

I want to count how many lists contains a specific le

2条回答
  •  日久生厌
    2021-01-26 07:44

    A simple list comprehension does the trick.

    >>> L=[['a', 'b', 'a'], ['a', 'b', 'c'], ['a']]
    >>> ['a' in x for x in L]
    [True, True, True]
    >>> ['b' in x for x in L]
    [True, True, False]
    

    Using the knowledge that True is considered 1:

    >>> sum('a' in x for x in L)
    3
    >>> sum('b' in x for x in L)
    2
    >>> sum('c' in x for x in L)
    1
    

提交回复
热议问题