【问题标题】:possible unique combinations between between two arrays(of different size) in python?python中两个数组(不同大小)之间可能的唯一组合?
【发布时间】:2016-07-23 06:13:48
【问题描述】:
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

【问题讨论】:

标签: python arrays python-3.x python-3.4 itertools


【解决方案1】:

您正在寻找.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)]

【讨论】:

    【解决方案2】:

    如果您想要的只是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']
    

    【讨论】:

      【解决方案3】:
      ["".join(v) for v in itertools.product(arr1, arr2)]
      #results in 
      ['OneThree', 'OneFour', 'TwoThree', 'TwoFour', 'FiveThree', 'FiveFour']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-07
        • 1970-01-01
        • 1970-01-01
        • 2020-04-04
        • 1970-01-01
        • 1970-01-01
        • 2013-11-12
        • 2021-06-13
        相关资源
        最近更新 更多