I have a nested list that I got from data that will be broken into sections to be uploaded to a database but have to be separate entries.
My nested list:
Master_List = [ a, [1,2,3], [1,2], d]
But I need to make it into six separate lists such as this:
list1 = [a, 1, 1, d]
list2 = [a, 1, 2, d]
list3 = [a, 2, 1, d]
list4 = [a, 2, 2, d]
etc.
I've tried iterating through the lists through the values of the list, but I'm confused since not all the master list indices will have more than one value. How do can I build these separate lists to be used?
When I tried just iterating through the lists and creating separate lists it became a convoluted mess.
Edit: Coldspeed's solution is exactly what I needed. Now I just use the dictionary to access the list I want.
The easiest way to do this would be using itertools.product
.
from itertools import product
out = {'list{}'.format(i) : list(l) for i, l in enumerate(product(*Master_List), 1)}
print(out)
{'list1': ['a', 1, 1, 'd'],
'list2': ['a', 1, 2, 'd'],
'list3': ['a', 2, 1, 'd'],
'list4': ['a', 2, 2, 'd'],
'list5': ['a', 3, 1, 'd'],
'list6': ['a', 3, 2, 'd']}
Unfortunately, you cannot create a variable number of variables without the use of a dictionary. If you want to access listX
, you'll access the out
dictionary, like this:
out['listX']