Mik*_*ike 5 python python-itertools
我有一份清单清单.使用itertools,我基本上在做
产品结果([A,B],[C,D],[E,F,G]):#test每个结果
结果是所需的产品,每个结果包含每个列表中的一个元素.我的代码逐个元素地测试每个结果,寻找第一个(和最好的)'好'的结果.可以测试非常大的数字.
假设我正在测试第一个结果'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
Run Code Online (Sandbox Code Playgroud)
但是,如果您拥有的集合数量是可变的,则使用递归函数(回溯):
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, [])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
801 次 |
| 最近记录: |