假设我有三个列表
[-1,0,1,2]
[0,1]
[a,b,c]
我想获得一个列表
[-1,0,a]
[-1,0,b]
[-1,0,c]
[-1,1,a]
[-1,1,b]
[-1,1,c]
[0,0,a]
[0,0,b]
[0,0,c]
...
如何编写python函数来实现这个目标?
答案 0 :(得分:2)
您可以使用itertools.product()
:
from itertools import product
from pprint import pprint
l = [[-1, 0, 1, 2], [0, 1], ['a', 'b', 'c']]
result = list(product(*l))
pprint(result)
结果:
[(-1, 0, 'a'),
(-1, 0, 'b'),
(-1, 0, 'c'),
(-1, 1, 'a'),
(-1, 1, 'b'),
(-1, 1, 'c'),
(0, 0, 'a'),
(0, 0, 'b'),
(0, 0, 'c'),
(0, 1, 'a'),
(0, 1, 'b'),
(0, 1, 'c'),
(1, 0, 'a'),
(1, 0, 'b'),
(1, 0, 'c'),
(1, 1, 'a'),
(1, 1, 'b'),
(1, 1, 'c'),
(2, 0, 'a'),
(2, 0, 'b'),
(2, 0, 'c'),
(2, 1, 'a'),
(2, 1, 'b'),
(2, 1, 'c')]
答案 1 :(得分:1)
您可以使用列表理解
l1 = [-1,0,1,2]
l2 = [0,1]
l3 = ['a','b','c']
[[i,j,k] for i in l1 for j in l2 for k in l3]