To count in how many list, certain elements appeared

Advertisements

Several names that I want to count, in how many lists they appeared.

four_in_one = [['David','Ellen','Ken'],['Peter','Ellen','Joe'],['Palow','Ellen','Jack'],['Lily','Elain','Ken']]

for name in ['David','Ken','Kate']:
    for each_list in four_in_one:
        i = 0
        if name in each_list:
            i += 1
            print (name, i)

Output:

David 1
Ken 1
Ken 1

How can I output as below? Thank you.

David 1
Kate 0
Ken 2

>Solution :

  • Move the counter declaration outside the inner loop.
  • Print the result after the inner loop, rather than on each iteration of it.
for name in ['David','Ken','Kate']:
    i = 0
    for each_list in four_in_one:
        if name in each_list:
            i += 1
    print(name, i)

The code can also be shortened using sum.

i = sum(name in each_list for each_list in four_in_one)

Leave a ReplyCancel reply