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

Use Counter to count unique values in multiple lists

I have a list of lists and I’m trying to use Counter to get the number of unique words across all of the lists.

[[‘My’,
‘name’,
 ‘is’,
 ‘Joe’],
[‘My’,
 ‘name’,
 ‘is’,
 ‘Sally’],
[‘My’,
 ‘name’,
 ‘is’,
 ‘Mike’]]

If it were just the first list I think I could do this:

counter_object = Counter(my_list[0])
keys = counter_object.keys()
num_values = len(keys)

print(num_values)

But unsure about doing this for multiple. Any help is much appreciated, thanks.

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

Edit: The expected output is 6. Because unique words ‘My’,
‘name’, ‘is’, ‘Joe’, ‘Sally’, ‘Mike’ total to 6.

>Solution :

If I understand your question correctly, you want to count the unique items from each sublists.

# MM = is your list
from collections import Counter   

def count_unique(M):
    flats = [x for sub in M for x in sub]
   
    counts = Counter(flats)

    return len(counts.keys())



print(count_unique(MM))     # check it 
# 6
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