2017-05-25 83 views
2

我不確定我的問題是否正確,但我不知道如何解釋其他詞。 所以我有一些像列出如何從多個列表中獲取所有組合?

a = ['11', '12'] 
b = ['21', '22'] 
c = ['31', '32'] 

,我需要得到的東西,如:

result = [ 
    ['11', '21', '31'], 
    ['11', '21', '32'], 
    ['11', '22', '31'], 
    ['11', '22', '32'], 
    ['12', '21', '31'], 
    ['12', '21', '32'], 
    ['12', '22', '31'], 
    ['12', '22', '32'] 
] 
+0

重複:從挑多個列表組合(https://stackoverflow.com/q/15305719/1324033) – Sayse

+0

請嘗試研究你的問題自報家門,複製你的問題的標題爲谷歌產生多個副本。 – Sayse

+0

如果所有列表看起來像二進制計數系統,那麼所有列表的長度都是兩個,所以您可以使用算法來實現,但是使用itertools的帖子是正確的。 –

回答

3

用戶itertoolscombinations

import itertools 
a = ['11', '12'] 
b = ['21', '22'] 
c = ['31', '32'] 
list(itertools.combinations(itertools.chain(a,b,c), 3)) 
[('11', '12', '21'), ('11', '12', '22'), ('11', '12', '31'), ('11', '12', '32'), ('11', '21', '22'), ('11', '21', '31'), ('11', '21', '32'), ('11', '22', '31'), ('11', '22', '32'), ('11', '31', '32'), ('12', '21', '22'), ('12', '21', '31'), ('12', '21', '32'), ('12', '22', '31'), ('12', '22', '32'), ('12', '31', '32'), ('21', '22', '31'), ('21', '22', '32'), ('21', '31', '32'), ('22', '31', '32')] 

product

list(itertools.product(a,b,c)) 
[('11', '21', '31'), ('11', '21', '32'), ('11', '22', '31'), ('11', '22', '32'), ('12', '21', '31'), ('12', '21', '32'), ('12', '22', '31'), ('12', '22', '32')] 
+0

'組合'留下了一些使用同一列表的2個元素的結果。 – Uriel

1

您需要itertools.product 它返回輸入迭代的笛卡爾乘積。

>>> a = ['11', '12'] 
>>> b = ['21', '22'] 
>>> c = ['31', '32'] 
>>> 
>>> from itertools import product 
>>> 
>>> list(product(a,b,c)) 
[('11', '21', '31'), ('11', '21', '32'), ('11', '22', '31'), ('11', '22', '32'), ('12', '21', '31'), ('12', '21', '32'), ('12', '22', '31'), ('12', '22', '32')] 

而且你可以使用列表理解到元組轉換成列表:

>>> [list(i) for i in product(a,b,c)] 
[['11', '21', '31'], ['11', '21', '32'], ['11', '22', '31'], ['11', '22', '32'], ['12', '21', '31'], ['12', '21', '32'], ['12', '22', '31'], ['12', '22', '32']] 
0
import itertools 
list(itertools.product(a,b,c)) 

或者使用numpy的

import numpy 
[list(x) for x in numpy.array(numpy.meshgrid(a,b,c)).T.reshape(-1,len(a))] 
0
import numpy as np  
np.array(np.meshgrid(a, b, c)).T.reshape(-1,3) 

編輯

import numpy as np 
len = 3 #combination array length 
np.array(np.meshgrid(a, b, c)).T.reshape(-1,len)