简体   繁体   English

两个列表中元素的组合

[英]Combinations of elements from two lists

I have two lists: 我有两个清单:

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

I want to take 3 elements from list1 and 2 elements from list2 to combine like the following (a total of 12 combinations): 我想从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]

This is the code I have that isn't working: 这是我不起作用的代码:

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' 

Use a combination of itertools functions combinations , product and chain : 使用itertools功能combinationsproductchain combinations

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]

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]]

Here you have the live example 这里有现场示例

Here's an approach that might work for you: 这是一种可能对您有用的方法:

>>> 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]]

You can use nested loops.Here is the code without any library(works only if you're leaving one element from each list!) 您可以使用嵌套循环,这是不带任何库的代码(仅当您从每个列表中保留一个元素时才有效!)

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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM