Ben Millar
Ben Millar

Reputation: 13

Python3 List Comprehension for n lists

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

Answers (2)

a_jelly_fish
a_jelly_fish

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

Andrej Kesely
Andrej Kesely

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

Related Questions