【问题标题】:Python: running tally of iterator values without building a list [duplicate]Python:在不构建列表的情况下运行迭代器值的计数[重复]
【发布时间】:2019-02-22 13:40:00
【问题描述】:

我想计算迭代器的唯一值,但不必先构建列表。使用列表,例如:

from collections import Counter
from itertools import combinations

my_counts = Counter([sum(x) for x in combinations([1,2,3,4,5])],2)

但在上面,创建了一个列表,然后应用了Counter。但是有没有办法保持一个连续的计数,这样整个列表就不需要存储在内存中了?

【问题讨论】:

  • 哦,好吧!多么简单的解决方案。谢谢!

标签: python iterator


【解决方案1】:

只需为 Counter 提供一个生成器表达式,而不是 list

my_counts = Counter(sum(x) for x in combinations([1,2,3,4,5], 2))

甚至更短(但map 在 Python3 中只返回一个生成器):

my_counts = Counter(map(sum, combinations([1,2,3,4,5], 2)))

这不会先在内存中建立一个列表。

【讨论】:

    猜你喜欢
    • 2021-06-15
    • 1970-01-01
    • 2018-03-18
    • 2017-09-10
    • 2016-08-14
    • 2019-01-12
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多