这是您想要的示例:
B = [10, 15, 20, 5]
F = [lambda x: x,
lambda x: x * x,
lambda x: x * 2 - 5]
def dostuff(i0, i1, i2, i3):
print((i0, i1, i2, i3))
expected = []
for i0 in range(0, B[0]):
for i1 in range(F[0](i0), B[1]):
for i2 in range(F[1](i1), B[2]):
for i3 in range(F[2](i2), B[3]):
expected.append([i0, i1, i2, i3])
我找到了这样的递归解决方案:
def iter_rec(found, fL, bL):
if fL and bL:
ik = found[-1] if found else 0
fk = fL[0]
bk = bL[0]
for i in range(fk(ik), bk):
for item in iter_rec(found + [i], fL[1:], bL[1:]):
yield item
else:
yield found
# prepend the null function to ensure F and B have the same size
F = [lambda x: 0] + F
current = [item for item in iter_rec([], F, B)]
我们有同样的结果。
assert expected == current