Search code examples
pythonlistcounteriterable

Python convert Counter object into list of ordinals


I think this should have a relatively simple solution.

I have a Counter object and, from it, I want to make a list composed of integers that represent the ordinal values of each key in the Counter object.

Illustration of what I mean:

Let's say this is my counter object -

Counter(elems)

Counter({'elem1': 13,
         'elem2': 13})

From this, I want to generate the following type of "ordinal" list:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

I've tried a few things, such as this:

ord_list = [i for i in range(1, v + 1) for k, v in Counter(elems).items()]

But the closest I keep getting is [1, 1, 2, 2, 3, 3, 4, 4..., 13, 13] rather than what I'm looking for.

What blindingly obvious thing am I missing? Thanks everyone.


Solution

  • You are missing the second loop that will add each individual number from every range to the outer list. Also, keep in mind it is not needed to iterate over items because you don't use the keys anywhere so just iterate over values.

    d = {'elem1': 13,
         'elem2': 13}
    
    print([num for v in d.values() for num in range(1, v + 1)])
    

    Or you can use itertools.chain to flatten the sublists for, in my opinion, a longer solution but more readable/descriptive:

    from itertools import chain
    
    d = {'elem1': 13,
         'elem2': 13}
    
    print(list(chain.from_iterable(range(1, v + 1) for v in d.values())))