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

cigdeys3  于 2022-12-06  发布在  Python
关注(0)|答案(2)|浏览(141)

我有麻烦让这个工作,任何帮助将不胜感激。我想有一个可变数量的嵌套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循环的变量数量。

eufgjt7s

eufgjt7s1#

你需要的是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))
bttbmeg0

bttbmeg02#

尝试使用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

相关问题