![](/img/trans.png)
[英]How can I find all the possible combinations of a list of lists (in Python)?
[英]How to find all the possible combinations of a range in Python?
这比 Python 更像是一个数学问题,但是如果我的范围是 0-100,我将如何通过 go 迭代所有可能的范围? 例如,下限可以是 0,然后上限可以是 1-100 之间的任何值,以此类推。
这样的事情会涵盖所有可能性吗?
lower = 0
upper = 100
for i in range(0,100):
for z in range(lower,upper):
print("Range is" + str(z) +":" + str(upper))
lower = lower +1
upper = upper -1
itertools.combinations(iterable, r)
从输入可迭代返回 r 元素的长度子序列。
根据输入可迭代的 >order 以字典顺序发出组合元组。 因此,如果输入的可迭代对象已排序,则 > 组合元组将按排序顺序生成。
元素根据其 position 而非其值被视为唯一。 所以>如果输入元素是唯一的,那么每个>组合中不会有重复值。
import itertools
arr = list(itertools.combinations(range(1,100), 2))
arr = []
for i in range(1,101):
for j in range(1,101):
arr.append((i,j))
print(arr)
您的问题基本上是 0-100 的 2 个数字的所有组合。 所以 100 选择了 2 种不同的组合。 Python 为此具有itertools.combinations
:
for lower, upper in itertools.combinations(range(100), 2):
# do something with lower and upper
如果您想实现自己的某些东西(不想像其他答案中提到的那样使用itertools
),这里有一些可行的方法:
lower = 0
upper = 10
for range_size in range(1, upper-lower+1):
for j in range(lower, upper):
if j+range_size > upper:
break
print(f"Range: [{j}, {j+range_size}]")
外部循环迭代所有可能的范围size
,可以小到1
也可以大到upper - lower
。 请注意, +1
是为了确保上限也包含在range
中。
然后内部循环从lower
开始并print
所有大小范围range_size
。
编辑:如果你想得到一个排序的 output 像itertools.combinations
,你可以将值存储在一个数组中并对该数组进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.