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 =  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 =  * 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 = a row = b row = c row = d row = e row = A row = B row = C row = D row = 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.
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 =  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: