How to count the occurrences of single items in a list of lists in descending order?

Question:

x=[['apple', 'banana', 'carrot'],
['apple', 'banana'],
['banana', 'carrot']]

I want the result to look like this:

dict  = {'banana': 3,'apple': 2, 'carrot': 2}
Asked By: eliza nyambu

||

Answers:

You can "flatten" your x, and then just count, while iterating over unique elements of the (flat) x:

x = [['apple', 'banana', 'carrot'],
    ['apple', 'banana'],
    ['banana', 'carrot']]

flat_x = [a for b in x for a in b]
res = {a: sum(b == a for b in flat_x) for a in set(flat_x)}
print(res)
# {'carrot': 2, 'apple': 2, 'banana': 3}

Another way to flatten-out the list-of-lists is to use chain from itertools, so you can use:

from itertools import chain
flat_x = list(chain(*x))
Answered By: ShlomiF

One-liner solution (if you don’t mind the import):

import collections

lists = [
    ['apple', 'banana', 'carrot'],
    ['apple', 'banana'],
    ['banana', 'carrot']    
]

print(collections.Counter(
    item for sublist in lists for item in sublist).most_common())

Documentation: Counter.most_common, generator expressions.

Answered By: user3840170
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.