Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

To count in how many list, certain elements appeared

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading