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

2024-04-19 17:42:03 发布

您现在位置: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


Tags: output数组onethreefouritertoolsfivetwo
3条回答

如果您只需要OneThree,OneFour,TwoThree,TwoFour,FiveThree,FiveFour,那么一个双for循环将为您实现以下目的:

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


OneThree
OneFour
TwoThree
TwoFour
FiveThree
FiveFour

或者如果您希望结果显示在列表中:

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

您正在寻找^{}

从医生那里可以看到:

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

样本代码:

^{pr2}$

要组合它们:

# This is the full code
import itertools

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

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

相关问题 更多 >