Reputation: 13
I have a way of iterating through my lists as I wish as follows:
a = ["1","2","3","4","5","6","7","8","9","10"]
b = ['A','B','C','D','E','F','G','H','I','J']
c = ["11","12","13","14","15","16","17","18","19","20"]
for x, y, z in [(x,y,z) for x in a for y in b for z in c]:
print(x,y,z)
Output:
1 A 11
1 A 12
1 A 13
1 A 14
1 A 15
1 A 16
1 A 17
1 A 18
1 A 19
1 A 20
1 B 11
1 B 12
1 B 13
1 B 14
...etc
But how can I achieve the same result if my lists are stored in a list and there are n lists? e.g.
main_list=[["1","2","3","4","5","6","7","8","9","1"],['A','B','C','D','E','F','G','H','I','J'],["11","12","13","14","15","16","17","18","19","20"],['k','l','m','n','o','p','q','r','s','t']]
Thanks in advance.
Upvotes: 1
Views: 34
Reputation: 490
For the example, the below gives the required combinations.
import itertools
list(itertools.product(*(a,b,c)))
For the mainlist -
main_list=[["1","2","3","4","5","6","7","8","9","1"],['A','B','C','D','E','F','G','H','I','J'],["11","12","13","14","15","16","17","18","19","20"],['k','l','m','n','o','p','q','r','s','t']]
combintns = list(itertools.product(*main_list))
# in case you're specific about output format/appearance
for i in combintns:
print(i[0],i[1],i[2],i[3])
Upvotes: 0
Reputation: 195553
Look at itertools.product
:
a = ["1","2","3","4","5","6","7","8","9","10"]
b = ['A','B','C','D','E','F','G','H','I','J']
c = ["11","12","13","14","15","16","17","18","19","20"]
from itertools import product
all_lists = [a, b, c]
for c in product(*all_lists):
print(c)
Prints:
('1', 'A', '11')
('1', 'A', '12')
('1', 'A', '13')
('1', 'A', '14')
('1', 'A', '15')
('1', 'A', '16')
('1', 'A', '17')
('1', 'A', '18')
('1', 'A', '19')
('1', 'A', '20')
('1', 'B', '11')
... and so on.
Upvotes: 1