2

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]
Isbister
  • 906
  • 1
  • 12
  • 30

3 Answers3

3
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.

Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
  • Python 3.6+ though. – Jeff Mercado Jan 18 '18 at 16:12
  • @JeffMercado Maybe, maybe not. – Stefan Pochmann Jan 18 '18 at 16:13
  • you're right! but what Jeff meant is that it doesn't preserve the order of the list. so it gives a different result in python < 3.6 where dicts are unordered. megets: `[0.0, 1.0, 2.0, 3.0, 3.0, 3.0, 3.0, -1.0, -3.0, -3.0, -3.0, -3.0, -2.0]` – Jean-François Fabre Jan 18 '18 at 16:14
  • well, the list can probably be sorted afterwards if order matters but order is the natural order of floats. – Jean-François Fabre Jan 18 '18 at 16:17
  • @Jean-FrançoisFabre Yeah I know, but I don't think it's clear whether order should be "preserved". I mean, he talks about the "original list", and who creates a Counter from a sorted list? Plus with 3.6+ it does preserve. – Stefan Pochmann Jan 18 '18 at 16:17
  • @Jean-FrançoisFabre Fair point, but that's just another reason to upgrade. :) Guido has promised that `dict` will from now on retain insertion order. OTOH, if the original list is sorted, we just need to wrap the `.elements()` call in sorted instead of `list`. – PM 2Ring Jan 18 '18 at 16:17
  • anyway I like that answer. – Jean-François Fabre Jan 18 '18 at 16:18
  • Me too. I was about to post it (but using `[*Counter(dict(a)).elements()]`) but I noticed that Stefan had ninja'd me. :) – PM 2Ring Jan 18 '18 at 16:20
  • @PM2Ring Ah yes, `[*...]`. Somehow I rarely think of that. Maybe that's my subconscious rejecting it for some reason :-) – Stefan Pochmann Jan 18 '18 at 16:23
3

You can use the following nested comprehension:

lst = [(-3.0, 4), ..., (3.0, 4)]
[x for x, count in lst for _ in range(count)]
# [-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]
user2390182
  • 72,016
  • 6
  • 67
  • 89
2

You can try this:

s = [(-3.0, 4), (-2.0, 1), (-1.0, 1), (0.0, 1), (1.0, 1), (2.0, 1), (3.0, 4)]
final_s = [i for b in [[a]*b for a, b in s] for i in b]

Output:

[-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]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102