简体   繁体   English

检索collections.Counter输出的输入

[英]retrieve input of collections.Counter output

Not sure if the title is correct but. 不确定标题是否正确但是。

Lets say you have a list that would look like the output from a Counter object. 假设您有一个类似于Counter对象输出的列表。

[(-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]
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. 因此,如果您确实拥有一个Counter ,只需直接询问它的elements

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]

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM