简体   繁体   English

如何在列表中一一创建元素的组合?

[英]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 combinations itertools.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.

相关问题 我如何从一个列表中创建一个字典,其中键是索引,值是列表的一个一个的实际元素? - How can I create a dictionary from a list where the keys are the indexes and the values are the actual elements of the list one by one? 如何获取列表的所有组合,其中两个相邻的元素可以成为一个元素 - How to get all combinations of a list where two elements next to each other can become one element 如何测试一个列表的两个元素,如果它们相等,则将一个列表的元素放到新列表中 - How can I test two elements of one list and if they are equivalent place the element of one list into a new list 如何检查数字是否可以被列表中的元素之一整除(Python)? - How can I check if a number is divisible by one of the elements in a list (Python)? 如何在列表元素之前和之后放置一个空格? - How I can put one space before and after list elements? 如何连接列表元素以创建一个字符串? - How to join list elements to create one string? 我如何将一个列表的元素拆分为另一个列表的元素,但按照它们在列表中的显示顺序 - how can i split the elements of one list by the elements of another list but in the order they are presented in the lists 如何以另一个列表中的元素为条件修改一个列表中的元素? - How can I modify elements in one list conditional on the elements in another list? 如何将一个列表中的元素插入到另一个列表中,生成所有可能的组合 - How to insert elements from one list to another generating all possible combinations 如何一一打印 Python 列表中的元素? - How do I print elements in a Python list one by one?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM