Skip to content
Advertisement

Python: Counting occurrences of List element within List

I’m trying to count the number of occurrences of elements within a list, if such elements are also lists. The order is also important.

[PSEUDOCODE]

lst = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['a', 'b', 'c'], ['c', 'b', 'a'] ]
print( count(lst) )


> { ['a', 'b', 'c'] : 2, ['d', 'e', 'f']: 1, ['c', 'b', 'a']: 1 }

One important factor is that ['a', 'b', 'c'] != ['c', 'b', 'a']

I have tried:

from collections import counter
print( Counter([tuple(x) for x in lst]) )
print( [[x, list.count(x)] for x in set(lst)] )

Which both resulted in ['a', 'b', 'c'] = ['c', 'b', 'a'], one thing i didn’t want

I also tried:

from collections import counter
print( Counter( lst ) )

Which only resulted in error; since lists can’t be used as keys in dicts.

Is there a way to do this?

Advertisement

Answer

You can’t have list as a key to the dict because dictionaries only allows immutable objects as it’s key. Hence you need to firstly convert your objects to tuple. Then you may use collection.Counter to get the count of each tuple as:

>>> from collections import Counter
>>> my_list = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['a', 'b', 'c'], ['c', 'b', 'a'] ]

#            v to type-cast each sub-list to tuple
>>> Counter(tuple(item) for item in my_list)
Counter({('a', 'b', 'c'): 2, ('d', 'e', 'f'): 1, ('c', 'b', 'a'): 1})
Advertisement