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

Count occurrences of list element in nested list

I have a list like this:

list_all = [['car', '123464', '4322445'],   ['car', '64346', '643267'], ['bicycle','1357','78543'], 
        ['bicycle', '75325', '75425'],
        ['car', '8652', '652466'], ['taxi', '653367', '63226'], 
        ['taxi', '96544', '22267'], ['taxi', '86542222', '54433'],     
        ['motorcycle', '675422', '56312'], ['motorcycle', '53225', '88885'], 
        ['motorcycle', '773345', '9977'], 
        ['motorcycle', '3466', '987444']]

I want the result like this:

result = [['car', 3], ['bicycle', 2], ['taxi', 3], ['motorcycle', 4]]

The new list should return the count of the elements based on the first element. I have tried in this way but it doesn’t work:

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

new = []
for item in list_all:
    if item[0] != [new[0] for el in new]:
        new.append(item)
print(new)

I’m new to Python. Any help will be much appreciated. Thank you very much.

>Solution :

This is probably most easily achieved just using a Counter on the first element of each list:

from collections import Counter

c =Counter([l[0] for l in list_all])
list(c.items())

Output:

[('car', 3), ('bicycle', 2), ('taxi', 3), ('motorcycle', 4)]

If you really want a list of lists (as opposed to a list of tuples) in the output, use a list comprehension over c.items():

[list(i) for i in c.items()]

Output:

[['car', 3], ['bicycle', 2], ['taxi', 3], ['motorcycle', 4]]
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