Home > OS >  Count occurrences of list element in nested list
Count occurrences of list element in nested list

Time:06-01

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:

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.

CodePudding user response:

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]]

CodePudding user response:

You can count the occurrences of the first item in each inner list inside of a dict and then use a list comprehension to convert the dictionary to a list.

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']]

def foo(arr):
    dct = dict()
    for lst in arr:
        if lst[0] in dct:
            dct[lst[0]]  = 1
        else:
            dct[lst[0]] = 1
    
    return [[k, v] for k,v in dct.items()]

print(foo(list_all))

Some people would prefer to use collections.defaultdict to do the same thing:

from collections import defaultdict

def foo2(arr):
    dct = defaultdict(int)
    for lst in arr:
        dct[lst[0]]  = 1
    return [[k,v] for k,v in dct.items()]

print(foo2(list_all))

Both of these will output:

[['car', 3], ['bicycle', 2], ['taxi', 3], ['motorcycle', 4]]
  • Related