我有一份清单。使用itertools,我基本上是在做
对于product(A,B,C,D,E,F,G)中的结果:#测试每个结果
结果是所需的产品,每个结果包含每个列表中的一个元素。我的代码逐个测试每个结果元素,寻找第一个(也是最好的)“好”结果。可以有一个非常非常大的数字来测试。
假设我正在测试第一个结果'ACE‘。比方说,当我测试第二个元素'C‘时,我发现'ACE’是一个糟糕的结果。不需要测试'ACF‘或'ACG’。我想直接从失败的ACE跳到尝试ADE。无论如何,要做到这一点而不只是把不想要的结果扔在地板上?
如果我使用嵌套的for循环来实现这一点,我将尝试操作循环中的for循环索引,这将不是很好……但是我确实想跳过测试很多结果。我可以在itertools中高效地跳过吗?
发布于 2010-11-16 12:48:18
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, [])https://stackoverflow.com/questions/4190966
复制相似问题