2

不确定标题是否正确,但。

假设您有一个看起来像 Counter 对象的输出的列表。

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

我怎么能回去得到原来的名单,因为

[-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]
4

3 回答 3

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

演示:

>>> 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]

因此,如果您确实有 a Counter,请直接询问它elements

于 2018-01-18T16:06:14.340 回答
3

您可以使用以下嵌套推导:

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]
于 2018-01-18T16:06:28.997 回答
2

你可以试试这个:

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]

输出:

[-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]
于 2018-01-18T16:04:05.063 回答