2016-11-28 57 views
-1

假設我有列表[['a', 'b', 'c'], ['d', 'e'], ['1', '2']]生成子列表中所有的Python可能的列表

我要生成列表,其中的第一個地方是從第一子列表的任何值,在第二 - 從第二等

於是,一對夫婦的例子:

['a', 'd', '1'] 
['b', 'd', '1'] 
['c', 'd', '1'] 
['a', 'e', '1'] 
['a', 'e', '2'] 
['b', 'e', '1'] 
['b', 'e', '2'] 

+0

列表要多長時間? – SamuelMacleod

+0

爲什麼不爲每個子列表生成一個隨機數(索引)並將該字符附加到新列表中? –

回答

2

您需要itertools.product()其返回inpur iterables的笛卡爾積:

>>> from itertools import product 
>>> my_list = [['a', 'b', 'c'], ['d', 'e'], ['1', '2']] 

#    v Unwraps the list 
>>> list(product(*my_list)) 
[('a', 'd', '1'), 
('a', 'd', '2'), 
('a', 'e', '1'), 
('a', 'e', '2'), 
('b', 'd', '1'), 
('b', 'd', '2'), 
('b', 'e', '1'), 
('b', 'e', '2'), 
('c', 'd', '1'), 
('c', 'd', '2'), 
('c', 'e', '1'), 
('c', 'e', '2')] 
相關問題