Search code examples
pythonpython-3.xpython-collections

retrieve input of collections.Counter output


Not sure if the title is correct but.

Lets say you have a list that would look like the output from a Counter object.

[(-3.0, 4), (-2.0, 1), (-1.0, 1), (0.0, 1), (1.0, 1), (2.0, 1), (3.0, 4)]

How could I go back and get the original list, as

[-3.0, -3.0, -3.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 3.0, 3.0, 3.0]

Solution

  • list(Counter(dict(a)).elements())
    

    Demo:

    >>> from collections import Counter
    >>> a = [(-3.0, 4), (-2.0, 1), (-1.0, 1), (0.0, 1), (1.0, 1), (2.0, 1), (3.0, 4)]
    >>> list(Counter(dict(a)).elements())
    [-3.0, -3.0, -3.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 3.0, 3.0, 3.0]
    

    So if you actually do have a Counter, just ask it for its elements directly.