检索 collections.Counter 输出的输入

retrieve input of collections.Counter output

不确定标题是否正确。

假设您有一个类似于计数器 object.

的输出的列表
[(-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]

你可以试试这个:

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

因此,如果您确实有一个 Counter,只需直接询问它的 elements

您可以使用以下嵌套理解:

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]