Python参数化列表中的所有组合

Python参数化列表中的所有组合,python,math,combinations,Python,Math,Combinations,大家好,我需要从列表中获取所有可能的参数组合 例如,我们可以有一个带有参数的列表,其中: 该参数只有一个值,在这种情况下,该参数将不会更改 参数有下限和上限,在这种情况下,参数将通过一些步骤从下限更改为上限 这是我的密码 from typing import List class Parameter: def __init__ (self, value = None, lowLimit = None, hightLimit = None, step = None): sel

大家好,我需要从列表中获取所有可能的参数组合

例如,我们可以有一个带有参数的列表,其中:

  • 该参数只有一个值,在这种情况下,该参数将不会更改

  • 参数有下限和上限,在这种情况下,参数将通过一些步骤从下限更改为上限

这是我的密码

from typing import List

class Parameter:
  def __init__ (self, value = None, lowLimit = None, hightLimit = None, step = None):
    self.value = value
    self.lowLimit = lowLimit
    self.hightLimit = hightLimit
    self.step = step

data: List[Parameter]  = [Parameter(1), Parameter(2, 2, 3, 1), Parameter(3, 3, 4, 1)]

def recursion(array: List[Parameter], skip: int):
  for index, value in enumerate(array):
    if index < skip: continue
    if value.lowLimit is not None and value.hightLimit is not None:
      temp = [it.value for it in array]
      init = value.lowLimit

      while init <= value.hightLimit :
        temp[index] = init
        init += value.step
        yield temp

def combination(array: List[Parameter]):
  for index, value in enumerate(array):
    if value.lowLimit is None and value.hightLimit is None : continue
    for d in recursion(array, index):
      yield d


for d in combination(data):
  print(d)

但是我的代码不起作用,我需要一些帮助来实现这个任务。有人能帮忙吗?

我不确定我是否真的理解您的要求,但我认为您可以将
参数
转换为
范围
,然后获得以下产品的
itertools.product

import itertools
data = [Parameter(1), Parameter(2, 2, 3, 1), Parameter(3, 3, 5, 2)]
ranges = [[p.value] if p.lowLimit is None else
          range(p.lowLimit, p.hightLimit+1, p.step) for p in data]
print(ranges)
# [[1], range(2, 4), range(3, 6, 2)]
for d in itertools.product(*ranges):
    print(d)
# (1, 2, 3), (1, 2, 5), (1, 3, 3), (1, 3, 5)

(注意:输出不同,因为我稍微更改了
数据
以实际使用
步骤!=1

最后两个是否为
[1,3,4]
[1,3,5]
?是的,它们应该是
import itertools
data = [Parameter(1), Parameter(2, 2, 3, 1), Parameter(3, 3, 5, 2)]
ranges = [[p.value] if p.lowLimit is None else
          range(p.lowLimit, p.hightLimit+1, p.step) for p in data]
print(ranges)
# [[1], range(2, 4), range(3, 6, 2)]
for d in itertools.product(*ranges):
    print(d)
# (1, 2, 3), (1, 2, 5), (1, 3, 3), (1, 3, 5)