python - 两个列表中元素的组合

标签 python list combinatorics

我有两个列表:

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' 

最佳答案

使用 itertools 的组合函数组合产品:

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

关于python - 两个列表中元素的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55252525/

相关文章:

python - 将数字转换为具有固定长度的二进制

c# - 列出日期,添加时间以列出 linq

algorithm - Grundy 的游戏扩展到两个以上的堆

python - Django channel 在 Windows 10 中安装失败

python - 使用 scrapy-splash 会显着影响抓取速度吗?

python - 尝试在不使用 Replace/Mapç 的情况下使用字符串附加列表元素

c++ - 如何使用 list::sort() 对 STL 列表对象进行排序,同时将我的自定义排序函数作为参数传递给 list::sort?

c# - 通用列表 c#

sql - 连接递归交叉连接

c++ - 是否有一种内存有效的方法来探索从输入排列生成的解决方案?