不确定标题是否正确但是。
假设您有一个类似于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]
答案 0 :(得分: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]
因此,如果您确实拥有Counter
,请直接向其elements
询问。
答案 1 :(得分: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]
答案 2 :(得分: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]