3

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.

qwr
  • 9,525
  • 5
  • 58
  • 102
Ali SAID OMAR
  • 6,404
  • 8
  • 39
  • 56

3 Answers3

7

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.

Adam Smith
  • 52,157
  • 12
  • 73
  • 112
2

You can use a nested list comprehension:

[i for a, b in p.items() for i in [a]*b]

Output:

['a', 'a', 'p']
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
1

With just for loop:

from collections import Counter

p = Counter({'a': 2, 'p': 1})
plist = []
for tup in p.items():
    for n in range(tup[1]):         
        plist.append(tup[0])
print(plist)

output:

['a', 'a', 'p']
>>> 
PythonProgrammi
  • 22,305
  • 3
  • 41
  • 34