Python 在可能值之间使用重复和规则进行排列

Python 在可能值之间使用重复和规则进行排列,python,iteration,constraints,out-of-memory,Python,Iteration,Constraints,Out Of Memory,我正在使用Python2.6并找到了函数 [in] a=[[1,2,3],[1,2,3]] [in] b=list(itertools.product(*a)) 其中a是一个列表列表,结果是一个列表,其中每个可能的组合都有元组,从a中的每个列表中取一个值。即 [out] [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)] 当我开始处理一个包含20个列表的列表时,问题就出现了(结果将是3**20个不

我正在使用Python2.6并找到了函数

[in] a=[[1,2,3],[1,2,3]]
[in] b=list(itertools.product(*a))
其中a是一个列表列表,结果是一个列表,其中每个可能的组合都有元组,从a中的每个列表中取一个值。即

[out]  [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
当我开始处理一个包含20个列表的列表时,问题就出现了(结果将是3**20个不同的元组并溢出内存)。 为了避免这些问题,我希望在生成之前或期间创建所有元组之后应用我正在应用的约束。 这些限制条件包括:

  • 总是连续两个2
  • 1的40%
  • 不是1后面的3或3后面的1

有人能帮我一个高级函数来做这类事情吗?

itertools的一个优点是它们不需要太多内存,只返回一个迭代器。 然后,您可以执行以下操作:

def valid_combination(combination):
    # Do whatever test you want here
    pass

def product_with_validation(validation_func, *element_list):
    for combination in itertools.product(*element_list):
        if validation_func(combination):
            yield combination

all_combinations = list(product_with_combo(product_with_validation, [1,2,3],[1,2,3])
带有组合的产品还返回一个迭代器,节省了大量内存

例:

结果:

[(2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9)]
附言:

itertools有一个函数,它的功能与产品_的功能几乎相同,带有_验证:,您可能想使用它,因为它可能比自定义编写的要快得多

[(2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9)]