首页 > 解决方案 > Python:在不构建列表的情况下运行迭代器值的计数

问题描述

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

from collections import Counter
from itertools import combinations

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

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

标签: pythoniterator

解决方案


只需输入Countera 生成器表达式而不是 a 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)))

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


推荐阅读