guys. I want to ask if there is any possible way which I can iterate multiple lists into the possible combinations of each element through python. I will illustrate the idea more detailed in the following. Thank you so much and wish whoever read this question have a nice day.
consider I have three lists as following:
list_01=['A','B','C','D']
list_02=[2, 2.5, 3, 3.5]
list_03=['2003','2004','2005','2006','2007','2008']
and the expectation should be like: A,2,2003 A,2,2004 A,2,2005 A,2,2006 A,2,2007 ... ... ... D,3.5,2006 D,3.5,2007 D,3.5,2008
something like this. I want to ask if there is any possible solutions for this none. Thank you so much.
CodePudding user response:
3 nested loops
You can can use the code below:
list_01=['A','B','C','D']
list_02=[2, 2.5, 3, 3.5]
list_03=['2003','2004','2005','2006','2007','2008']
for k in list_01:
for j in list_02:
for i in list_03:
print(k ',' str(j) ',' i)
CodePudding user response:
We can approach this with nested for loops.
list_01=['A','B','C','D']
list_02=[2, 2.5, 3, 3.5]
list_03=['2003','2004','2005','2006','2007','2008']
for i in range(len(list_01)):
for j in range(len(list_02)):
for k in range(len(list_03)):
print(list_01[i], list_02[j], list_03[k], sep = ',', end = ' ')
Once the third for loop goes through each value of list 3 by incrementing k each time the loop repeats, 'j', our iterator for list 2, increases by one, and we go through each value of list 3 again, this time, with the second element of list 2. From there, the same thing happens, but this time with the next element of the first list.