Skip to content Skip to sidebar Skip to footer

Python Count In A Sublist In A Nest List

x = [['a', 'b', 'c'], ['a', 'c', 'd'], ['e', 'f', 'f']] Let's say we have a list with random str letters. How can i create a function so it tells me how many times the letter 'a'

Solution 1:

You could flatten the list and use collections.Counter:

>>> import collections
>>> x = [['a', 'b', 'c'], ['a', 'c', 'd'], ['e', 'f', 'f']]
>>> d = collections.Counter(e for sublist in x for e in sublist)
>>> d
Counter({'a': 2, 'c': 2, 'f': 2, 'b': 1, 'e': 1, 'd': 1})
>>> d['a']
2

Solution 2:

import itertools, collectionsresult= collections.defaultdict(int)
for i in itertools.chain(*x):
    result[i] += 1

This will create result as a dictionary with the characters as keys and their counts as values.

Solution 3:

Just FYI, you can use sum() to flatten a single nested list.

>>> from collections import Counter
>>>
>>> x = [['a', 'b', 'c'], ['a', 'c', 'd'], ['e', 'f', 'f']]
>>> c = Counter(sum(x, []))
>>> c
Counter({'a': 2, 'c': 2, 'f': 2, 'b': 1, 'e': 1, 'd': 1})

But, as Blender and John Clements have addressed, itertools.chain.from_iterable() may be more clear.

>>> from itertools import chain
>>> c = Counter(chain.from_iterable(x)))
>>> c
Counter({'a': 2, 'c': 2, 'f': 2, 'b': 1, 'e': 1, 'd': 1})

Post a Comment for "Python Count In A Sublist In A Nest List"