Skip to main content
 首页 » 编程设计

python之当时组合列表 3 的元素

2024年11月01日10jackei

我很难理解如何组合列表中的元素。

我有:

a = [[1, 2], [3, 4, 5], [6], [7, 8, 9, 10]] 

我想通过从每个列表成员中获取元素来创建三元组 但总是包括第一个元素。这段代码完成了一半 工作:

r=[[]] 
for x in a[0:3]: 
    t = [] 
    for y in x: 
        for i in r: 
            t.append(i+[y]) 
r = t 

r

[[1, 3, 6], [2, 3, 6], [1, 4, 6], [2, 4, 6], [1, 5, 6], [2, 5, 6]] 

但我也想:

[[1,6,7], [1,6,8], [1,6,9] etc.]  

有人可以推荐一个好的方法吗?

请您参考如下方法:

使用 itertools :

import itertools 
 
a = [[1, 2], [3, 4, 5], [6], [7, 8, 9, 10]] 
for xss in itertools.combinations(a, 3): # pick 3 lists. 
    # xss => ([1, 2], [3, 4, 5], [6]) 
    #        ([1, 2], [3, 4, 5], [7, 8, 9, 10]) 
    #        ... 
 
    indexed = [enumerate(x) for x in xss] 
    # indexed => [[(0, 1), (1, 2)], [(0, 3), (1, 4), (2, 5)], [(0, 6)]] 
    #             ^^^^^^^^^^^^^^^^ list(enumerate([1, 2])) 
 
    for xs in itertools.product(*indexed): 
        # xs => ((0, 1), (0, 3), (0, 6)) 
        #       ((0, 1), (0, 3), (0, 7)) 
        #       ((0, 1), (0, 6), (0, 7)) 
        #        ... 
        if all(i > 0 for i, x in xs): # exclude no first item is selected. 
            continue 
        print [x for i, x in xs] 

更新对评论的回应。

import itertools 
 
a = [[1, 2], [3, 4, 5], [6], [7, 8, 9, 10]] 
for xss in itertools.combinations(a[1:], 2): 
    xss = (a[0],) + xss 
    indexed = [enumerate(x) for x in xss] 
    for xs in itertools.product(*indexed): 
        if all(i > 0 for i, x in xs): 
            continue 
        print [x for i, x in xs] 

输出:

[1, 3, 6] 
[1, 4, 6] 
[1, 5, 6] 
[2, 3, 6] 
[2, 4, 6] 
[2, 5, 6] 
[1, 3, 7] 
[1, 3, 8] 
[1, 3, 9] 
[1, 3, 10] 
[1, 4, 7] 
[1, 4, 8] 
[1, 4, 9] 
[1, 4, 10] 
[1, 5, 7] 
[1, 5, 8] 
[1, 5, 9] 
[1, 5, 10] 
[2, 3, 7] 
[2, 3, 8] 
[2, 3, 9] 
[2, 3, 10] 
[2, 4, 7] 
[2, 5, 7] 
[1, 6, 7] 
[1, 6, 8] 
[1, 6, 9] 
[1, 6, 10] 
[2, 6, 7] 
[2, 6, 8] 
[2, 6, 9] 
[2, 6, 10]