To count in how many list, certain elements appeared

Question:

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?

David 1
Kate 0
Ken 2
Asked By: Mark K

||

Answers:

  • 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)
Answered By: Unmitigated

Let Counter do the counting on a flatten list, then limit the resulting object by the names you’re looking for

from collections import Counter

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

res = Counter([i for sublist in four_in_one for i in sublist])
res = {name: res[name] for name in names}

print(res)

# {'David': 1, 'Ken': 2, 'Kate': 0}
Answered By: 0stone0
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.