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
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)
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}
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
- 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)
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}