python 中两个数组(不同大小)之间可能的唯一组合?
possible unique combinations between between two arrays(of different size) in python?
arr1=['One','Two','Five'],arr2=['Three','Four']
喜欢itertools.combinations(arr1,2)
给我们
('OneTwo','TwoFive','OneFive')
我想知道有没有办法将它应用于两个不同的数组?我的意思是 arr1 和 arr2。
Output should be OneThree,OneFour,TwoThree,TwoFour,FiveThree,FiveFour
如果您只想要 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']
您正在寻找.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)]
["".join(v) for v in itertools.product(arr1, arr2)]
#results in
['OneThree', 'OneFour', 'TwoThree', 'TwoFour', 'FiveThree', 'FiveFour']
arr1=['One','Two','Five'],arr2=['Three','Four']
喜欢itertools.combinations(arr1,2)
给我们('OneTwo','TwoFive','OneFive')
我想知道有没有办法将它应用于两个不同的数组?我的意思是 arr1 和 arr2。
Output should be OneThree,OneFour,TwoThree,TwoFour,FiveThree,FiveFour
如果您只想要 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']
您正在寻找.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)]
["".join(v) for v in itertools.product(arr1, arr2)]
#results in
['OneThree', 'OneFour', 'TwoThree', 'TwoFour', 'FiveThree', 'FiveFour']