【问题标题】:Combinations of elements from two lists两个列表中元素的组合
【发布时间】:2019-03-20 10:52:38
【问题描述】:

我有两个列表:

list1 = ["a", "b", "c", "d"]
list2 = [1, 2, 3]

我想取list1 中的3 个元素和list2 中的2 个元素进行如下组合(共12 个组合):

[a b c 1 2]
[a b c 1 3]
[a b c 2 3]
[a b d 1 2]
[a b d 1 3]
[a b d 2 3]
[a c d 1 2]
[a c d 1 3]
[a c d 2 3]
[b c d 1 2]
[b c d 1 3]
[b c d 2 3]

这是我没有工作的代码:

import itertools
from itertools import combinations 

def combi(arr, r): 
    return list(combinations(arr, r)) 

# Driver Function 
if __name__ == "__main__": 
    a = ["a", "b", "c", "d"] 
    r = 3
    a= combi(arr, r)
    print (a)
    b = [1, 2, 3]
    s =2
    b = combi(brr, s)
    print (b)
    crr = a + b
    print (crr)
    c = combi(crr, 2)
    print (c)
    for i in range(len(c)):
        for j in range(len(c)):
            print c[i][j]
            print '\n' 

【问题讨论】:

    标签: python list combinatorics


    【解决方案1】:

    使用itertools 函数combinationsproductchain 的组合:

    list1 = ["a", "b", "c", "d"]
    list2 = [1, 2, 3]
    
    import itertools
    
    comb1 = itertools.combinations(list1, 3)
    comb2 = itertools.combinations(list2, 2)
    result = itertools.product(comb1, comb2)
    result = [list(itertools.chain.from_iterable(x)) for x in result]
    

    结果:

    [['a', 'b', 'c', 1, 2],
     ['a', 'b', 'c', 1, 3],
     ['a', 'b', 'c', 2, 3],
     ['a', 'b', 'd', 1, 2],
     ['a', 'b', 'd', 1, 3],
     ['a', 'b', 'd', 2, 3],
     ['a', 'c', 'd', 1, 2],
     ['a', 'c', 'd', 1, 3],
     ['a', 'c', 'd', 2, 3],
     ['b', 'c', 'd', 1, 2],
     ['b', 'c', 'd', 1, 3],
     ['b', 'c', 'd', 2, 3]]
    

    这里有live example

    【讨论】:

      【解决方案2】:

      以下方法可能适合您:

      >>> from itertools import combinations
      >>> list1 = ["a", "b", "c", "d"]
      >>> list2 = [1, 2, 3]
      >>> [[*x, *y] for x in combinations(list1, 3) for y in combinations(list2, 2)]
      [['a', 'b', 'c', 1, 2], ['a', 'b', 'c', 1, 3], ['a', 'b', 'c', 2, 3], ['a', 'b', 'd', 1, 2], ['a', 'b', 'd', 1, 3], ['a', 'b', 'd', 2, 3], ['a', 'c', 'd', 1, 2], ['a', 'c', 'd', 1, 3], ['a', 'c', 'd', 2, 3], ['b', 'c', 'd', 1, 2], ['b', 'c', 'd', 1, 3], ['b', 'c', 'd', 2, 3]]
      

      【讨论】:

        【解决方案3】:

        您可以使用嵌套循环。这是没有任何库的代码(仅当您从每个列表中保留一个元素时才有效!)

        list3=[]
        for a in list1:
            st=''
            for t in list1:
                if(t!=a):
                    st=st+t+' '
            for b in list2:
                st1=''
                for m in list2:
                    if(m!=b):
                         st1=st1+m+' '
                list3.append(st+st1.strip())
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-31
          • 2020-07-19
          • 2015-11-12
          • 1970-01-01
          • 2017-07-26
          • 1970-01-01
          相关资源
          最近更新 更多