我有10个变量x1至x10,每个变量可能值的数量范围为1至256。
x1 = [1,10,20,23,12]
x2 = ['string0','string1','string3']
我需要生成所有可能的配置
1, string0,..... <till x10 value>
1, string1
1, string3
......
12, string0
12, string1
12, string3
我目前正被嵌套以遍历所有x1到x10,例如
for i in x1:
for j in x2:
......
print(i,j,k,.....)
输出不会超过三个或四个for循环。有没有更好的方法可以将所有可能的配置打印到文件中?
答案 0 :(得分:3)
使用product
模块中的itertools
方法:
>>> import itertools as it
>>> x1 = [1,10,20,23,12]
>>> x2 = ['string0','string1','string3']
>>> list(it.product(x1, x2))
[(1, 'string0'),
(1, 'string1'),
(1, 'string3'),
(10, 'string0'),
(10, 'string1'),
(10, 'string3'),
(20, 'string0'),
(20, 'string1'),
(20, 'string3'),
(23, 'string0'),
(23, 'string1'),
(23, 'string3'),
(12, 'string0'),
(12, 'string1'),
(12, 'string3')]
答案 1 :(得分:0)
仅是列表理解,对列表x1
和x2
进行迭代就足够了
>>> from pprint import pprint
>>> res = [(a,b) for a in x1 for b in x2]
>>> pprint(res)
[(1, 'string0'),
(1, 'string1'),
(1, 'string3'),
(10, 'string0'),
(10, 'string1'),
(10, 'string3'),
(20, 'string0'),
(20, 'string1'),
(20, 'string3'),
(23, 'string0'),
(23, 'string1'),
(23, 'string3'),
(12, 'string0'),
(12, 'string1'),
(12, 'string3')]