如何找到 Python 范围内所有可能的组合?

How to find all the possible combinations of a range in Python?

这比 Python 更像是一个数学问题,但如果我的范围是 0-100,我将如何遍历其中所有可能的范围?例如,下限可以是 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

您的问题基本上是 0-100 中 2 个数字的所有组合。所以 100 人选择 2 种不同的组合。 Python 为此 itertools.combinations

for lower, upper in itertools.combinations(range(100), 2):
    # do something with lower and upper
  1. 结帐itertools.combinations
itertools.combinations(iterable, r)

Return r length subsequences of elements from the input iterable.

The combination tuples are emitted in lexicographic ordering according to the >order of the input iterable. So, if the input iterable is sorted, the >combination tuples will be produced in sorted order.

Elements are treated as unique based on their position, not on their value. So >if the input elements are unique, there will be no repeat values in each >combination.

import itertools
arr = list(itertools.combinations(range(1,100), 2))
  1. 使用 For 循环

For loops

arr = []
for i in range(1,101):
    for j in range(1,101):
        arr.append((i,j))
print(arr)

如果您想实现自己的东西(不想像其他答案中提到的那样使用 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.

开始

编辑: 如果你想获得像 itertools.combinations 这样的排序输出,你可以将值存储在一个数组中并对该数组进行排序。