Python中嵌套for循环的可变数量



我有麻烦得到这个工作和任何帮助将非常感激。我想为下面的代码有一个可变数量的嵌套for循环。其思想是将所有可能的组合写入csv文件。

下面是我的代码:'
ka = [0.217, 0.445]
kb = [0.03, 0.05]
kc = [10]
kd = [0.15625, 0.7]
ke = [1.02, 0.78]
La = [0.15, 0.25]
Lb = [0.025, 0.075]
tc = [0.002, 0.007]
Ld = [0.025, 0.115]
Le = [0.07, 0.2]
NUMBER_OF_VARIABLES = 10
with open('test.csv', 'w') as file:
writer = csv.writer(file, lineterminator = 'n')
row = [0] * len(NUMBER_OF_VARIABLES)


for E in Le:
for D in Ld:                                    
for C in tc:
for B in Lb:
for A in La:
for e in ke:
for d in kd:
for c in kc:
for b in kb:
for a in ka:
row[0] = a
row[1] = b
row[2] = c
row[3] = d
row[4] = e
row[5] = A
row[6] = B
row[7] = C
row[8] = D
row[9] = E
writer.writerow(row)

'我的想法是,我希望能够添加更多或删除变量。每个字母的k和L是相关的。例如,添加另一个变量将包括一个Lf和kf。我不希望手动添加更多的循环。如果将变量结构做成一个列表会更好,则不必保留该变量结构。

我觉得我需要写一个递归函数,但我有麻烦弄清楚,任何帮助将非常感激。

我曾尝试导入csv文件,其中每行有一个变量,但无法找出for循环的变量数。

您需要的是itertools.product。它会为你处理这一切。

import itertools
ka = [0.217, 0.445]
kb = [0.03, 0.05]
kc = [10]
kd = [0.15625, 0.7]
ke = [1.02, 0.78]
La = [0.15, 0.25]
Lb = [0.025, 0.075]
tc = [0.002, 0.007]
Ld = [0.025, 0.115]
Le = [0.07, 0.2]
for row in itertools.product(ka,kb,kc,kd,ke,La,Lb,tc,Ld,Le):
writer.writerow(row)

你甚至可以在一行中完成:

writer.writerows(itertools.product(ka,kb,kc,kd,ke,La,Lb,tc,Ld,Le))

尝试使用itertools.product:

ka = [0.217, 0.445]
kb = [0.03, 0.05]
kc = [10]
kd = [0.15625, 0.7]
ke = [1.02, 0.78]
La = [0.15, 0.25]
Lb = [0.025, 0.075]
tc = [0.002, 0.007]
Ld = [0.025, 0.115]
Le = [0.07, 0.2]
from itertools import product
with open('test.csv', 'w') as file:
writer = csv.writer(file, lineterminator = 'n')
writer.writerows(product(ka, kb, kc, kd, ke, La,Lb, tc, Ld, Le)

正如你所看到的,Python有内置的工具来处理这种情况。否则,如果iterttols包不在那里,那么完成这类事情的方法是使用函数,然后递归地调用它们——比如

def product(*args):
if not args: return []
remainder = product(*args[1:])
result = []
for item in args[0]:
if remainder:
for part in remainder:
row = [item, *part]
result.append(row)
else:
result.append([item,])
return result

相关内容

  • 没有找到相关文章

最新更新