我有一个列表列表。使用itertools,我基本上是在做
对于产品结果([A,B],[C,D],[E,F,G]): # 测试每一个结果
结果是所需的产品,每个结果包含每个列表中的一个元素。我的代码逐个元素地测试每个结果,寻找第一个(也是最好的)“好”结果。可以有非常非常大的数字要测试。
假设我正在测试第一个结果“ACE”。假设当我测试第二个元素“C”时,我发现“ACE”是一个糟糕的结果。无需测试“ACF”或“ACG”。我想从失败的 ACE 直接跳到尝试 ADE。无论如何要做到这一点而不只是把不需要的结果扔在地板上?
如果我用嵌套的 for 循环实现它,我将尝试在循环内操作 for 循环索引,这不会很好……但我确实想跳过测试很多结果。我可以在 itertools 中高效地向前跳吗?
最佳答案
itertools 不是解决您所担心的问题的最佳方式。
如果您只有 3 组组合,只需循环,当您失败时,打破循环。 (如果您的代码很复杂,请设置一个变量并在外面中断。
for i1 in [A, B]:
for i2 in [C, D]:
for i3 in [E, F, G]:
if not test(i1, i2, i3):
break
但是,如果您拥有的集合数量是可变的,则使用递归函数(回溯):
inp_sets = ([A,B],[C,D],[E,F,G])
max_col = len(inp_sets)
def generate(col_index, current_set):
if col_index == max_col:
if test(current_set):
return current_set
else:
return None
else:
found = False
for item in inp_sets[col_index]:
res = generate(col_index+1, current_set + [item]):
if res:
return res
elif (col_index == max_col - 1):
# Here we are skipping the rest of the checks for last column
# Change the condition if you want to skip for more columns
return None
result = generate(0, [])
关于python itertools 向前跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4190966/