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

wie itertools.combinations(arr1,2) gibt uns
('OneTwo','TwoFive','OneFive')
Ich frage mich, ist es eine Möglichkeit, dies zu zwei verschiedenen arrays.?I bedeuten für arr1 und arr2 Anwendung.mögliche eindeutige Kombinationen zwischen zwei Arrays (unterschiedlicher Größe) in Python?

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

+0

Mögliches Duplikat [Generieren aller einzigartigen Paare Permutationen] (http://stackoverflow.com/questions/14169122/generating-all-unique-pair-permutations) –

Antwort

2

Sie suchen nach .product():

Vom doc, tut es dies:

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

Beispielcode:

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

sie kombinieren:

# 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

Wenn alles, was Sie wollten OneThree,OneFour,TwoThree,TwoFour,FiveThree,FiveFour ist dann eine doppelte for Schleife wird den Trick für Sie tun:

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


OneThree 
OneFour 
TwoThree 
TwoFour 
FiveThree 
FiveFour 

Oder wenn Sie das Ergebnis in einer Liste auswählen:

>>> [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']