[英]How can I create combinations of elements in a list one by one?
I have a list of elements [1, 2, 3, 4, 5], I want to generate combinations one by one, like [1, 2, 3], [2, 4, 5], etc. 我有一个元素列表[1、2、3、4、5],我想一个一个地生成组合,例如[1、2、3],[2、4、5]等。
I tried using itertools.combinations but that makes a list of all possible combinations, which takes up too much memory space. 我尝试使用itertools.combinations,但这列出了所有可能的组合,这会占用过多的内存空间。
How do I access each new combination right when it is generated? 生成新组合时,如何访问每个新组合?
How do I access each new combination right when it is generated?
生成新组合时,如何访问每个新组合?
Use a for
loop, like so: 使用
for
循环,如下所示:
import itertools
for a, b, c in itertools.combinations(range(1, 101), 3):
if a**2 + b**2 == c**2:
print(a, b, c)
itertools.combinations
makes a list of all possible combinationsitertools.combinations
列出所有可能的组合
No, it doesn't. 不,不是。
itertools.combinations()
is a generator function . itertools.combinations()
是一个生成器函数 。 When used in a for
loop, only one result is returned at a time. 在
for
循环中使用时,一次仅返回一个结果。 No list
of all the results is ever created. 永远不会创建所有结果的
list
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.