2016-07-23 49 views
2
arr1=['One','Two','Five'],arr2=['Three','Four'] 

itertools.combinations(arr1,2)給我們
('OneTwo','TwoFive','OneFive')
我想知道是否有任何應用這兩種不同的arrays.?I意味着ARR1和ARR2方式。python中兩個數組(不同大小)之間可能的獨特組合?

Output should be OneThree,OneFour,TwoThree,TwoFour,FiveThree,FiveFour

+0

的[生成所有獨特的對排列]可能的複製(http://stackoverflow.com/questions/14169122/generating-all-unique-pair-permutations) –

回答

2

您在尋找.product()

從文檔,它這樣做:

product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy 
product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111 

示例代碼:

>>> x = itertools.product(arr1, arr2) 
>>> for i in x: print i 
('One', 'Three') 
('One', 'Four') 
('Two', 'Three') 
('Two', 'Four') 
('Five', 'Three') 
('Five', 'Four') 

要結合他們:

# This is the full code 
import itertools 

arr1 = ['One','Two','Five'] 
arr2 = ['Three','Four'] 

combined = ["".join(x) for x in itertools.product(arr1, arr2)] 
1

如果您想讓所有的OneThree,OneFour,TwoThree,TwoFour,FiveThree,FiveFour然後雙for循環會做的伎倆爲您提供:

>>> for x in arr1: 
     for y in arr2: 
      print(x+y) 


OneThree 
OneFour 
TwoThree 
TwoFour 
FiveThree 
FiveFour 

或者,如果你想要的結果的列表:

>>> [x+y for x in arr1 for y in arr2] 
['OneThree', 'OneFour', 'TwoThree', 'TwoFour', 'FiveThree', 'FiveFour'] 
1
["".join(v) for v in itertools.product(arr1, arr2)] 
#results in 
['OneThree', 'OneFour', 'TwoThree', 'TwoFour', 'FiveThree', 'FiveFour'] 
相關問題