我希望按照以下方式遍历列表:
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)
输出:
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
但是,如果我的列表存储在一个列表中并且有n个列表,如何获得相同的结果?例如
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']]
提前感谢。
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)
对于示例,以下给出了所需的组合。
('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.
对于主列表-
import itertools
list(itertools.product(*(a,b,c)))