I am having trouble getting this to work and any help would be greatly appreciated. I want to have a variable number of nested for loops for the following code. The idea is to write every combination possible to a csv file.
here is my code: `
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)
` the idea is I would like to be able to add more or remove variables. the k and L of each letter are related. For example to add another variable would include a Lf and kf. I would like to do it without manually adding more loops. The variable structure does not have to remain if it would be better to make it one list.
I feel like I need to write a recursive function but am having trouble figuring this out, any help would be greatly appreciated.
I have tried importing a csv file where each line has a variable but can not figure out the variable number of for loops.
CodePudding user response:
What you need is itertools.product
. It will handle all of this for you.
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)
You can probably even do that in a single line:
writer.writerows(itertools.product(ka,kb,kc,kd,ke,La,Lb,tc,Ld,Le))
CodePudding user response:
Try using 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)
As you can see - Python does have built-in tools to deal with this situations. Otherwise, if the iterttols package was not there, the way to do this kind of thing is by using functions, and calling then recursively - something like
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