pythoncounterpython-collections

Python Counter to list of elements


Now to flatten Counter element i'm using the code

import operator
from collections import Counter
from functools import reduce

p = Counter({'a': 2, 'p': 1})
n_p = [[e] * p[e] for e in p]
f_p = reduce(operator.add, n_p)

# result: ['a', 'a', 'p']

So i'm wonder, if it could be done more directly.


Solution

  • This is Counter.elements

    p = Counter({'a': 2, 'p': 1})
    p.elements()  # iter(['a', 'a', 'p'])
    list(p.elements())  # ['a', 'a', 'p']
    ''.join(p.elements())  # 'aap'
    

    Note that (per the docs)

    Elements are returned in arbitrary order

    So you may want to sort the result to get a stable order.