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}
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))
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.
x=[['apple', 'banana', 'carrot'],
['apple', 'banana'],
['banana', 'carrot']]
I want the result to look like this:
dict = {'banana': 3,'apple': 2, 'carrot': 2}
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))
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.