python中两个不同大小的数组之间可能的唯一组合?

时间:2020-12-18 12:06:42
arr1=['One','Two','Five'],arr2=['Three','Four']

like itertools.combinations(arr1,2) gives us
('OneTwo','TwoFive','OneFive')
I was wondering is there any way applying this to two different arrays.?I mean for arr1 and arr2.

比如itertools.combination (arr1,2)给出了我们('OneTwo','TwoFive','OneFive')。arr1和arr2。

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

输出应该OneThree OneFour、TwoThree TwoFour,FiveThree FiveFour

3 个解决方案

#1


2  

You are looking for .product():

您正在寻找。product():

From the doc, it does this:

从医生那里,它做到了:

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

Sample code:

示例代码:

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

To combine them:

结合:

# This is the full code
import itertools

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

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

#2


1  

If all you wanted is OneThree,OneFour,TwoThree,TwoFour,FiveThree,FiveFour then a double for loop will do the trick for you:

如果你想要的是一三,一份,二份,二份,五份,五份,五份,五份,四份,那么一个双重循环就可以帮你做到:

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


OneThree
OneFour
TwoThree
TwoFour
FiveThree
FiveFour

Or if you want the result in a list:

或者如果你想要一个列表中的结果:

>>> [x+y for x in arr1 for y in arr2]
['OneThree', 'OneFour', 'TwoThree', 'TwoFour', 'FiveThree', 'FiveFour']

#3


1  

["".join(v) for v in itertools.product(arr1, arr2)]
#results in 
['OneThree', 'OneFour', 'TwoThree', 'TwoFour', 'FiveThree', 'FiveFour']

#1


2  

You are looking for .product():

您正在寻找。product():

From the doc, it does this:

从医生那里,它做到了:

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

Sample code:

示例代码:

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

To combine them:

结合:

# This is the full code
import itertools

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

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

#2


1  

If all you wanted is OneThree,OneFour,TwoThree,TwoFour,FiveThree,FiveFour then a double for loop will do the trick for you:

如果你想要的是一三,一份,二份,二份,五份,五份,五份,五份,四份,那么一个双重循环就可以帮你做到:

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


OneThree
OneFour
TwoThree
TwoFour
FiveThree
FiveFour

Or if you want the result in a list:

或者如果你想要一个列表中的结果:

>>> [x+y for x in arr1 for y in arr2]
['OneThree', 'OneFour', 'TwoThree', 'TwoFour', 'FiveThree', 'FiveFour']

#3


1  

["".join(v) for v in itertools.product(arr1, arr2)]
#results in 
['OneThree', 'OneFour', 'TwoThree', 'TwoFour', 'FiveThree', 'FiveFour']