如何将元素从一个列表插入到另一个列表生成所有可能的组合

How to insert elements from one list to another generating all possible combinations

大家好,我需要一些有关 python 列表的帮助。假设我有两个列表。

a = [3,1,5]
b = [2,4]

我想要的是连续插入列表b的元素(不改变a的顺序)生成新列表。例如。

ans = [[2,4,3,1,5],[2,3,4,1,5],[2,3,1,4,5],[2,3,1,5,4],[3,2,4,1,5]...]

感谢您的帮助,希望我能够正确表达自己的意思。

这不是最简洁的方法,但我的意思是:

from itertools import permutations

a = [3,1,5]
b = [2,4]

def a_order_is_same(perm):
    i3, i1, i5 = perm.index(3), perm.index(1), perm.index(5)
    return i3 < i1 < i5

ans = [p for p in permutations(a+b) if a_order_is_same(p)]

for p in ans:
    print(p)

--------------------------------------------------

(3, 1, 5, 2, 4)
(3, 1, 5, 4, 2)
(3, 1, 2, 5, 4)
(3, 1, 2, 4, 5)
(3, 1, 4, 5, 2)
(3, 1, 4, 2, 5)
(3, 2, 1, 5, 4)
(3, 2, 1, 4, 5)
(3, 2, 4, 1, 5)
(3, 4, 1, 5, 2)
(3, 4, 1, 2, 5)
(3, 4, 2, 1, 5)
(2, 3, 1, 5, 4)
(2, 3, 1, 4, 5)
(2, 3, 4, 1, 5)
(2, 4, 3, 1, 5)
(4, 3, 1, 5, 2)
(4, 3, 1, 2, 5)
(4, 3, 2, 1, 5)
(4, 2, 3, 1, 5)

我给你另一个选择。

import itertools 
                        
a = [3,1,5]
b = [2,4]
            
c = [b +[a]][0] #0 to get only one level of nested

perm = [x for x in itertools.permutations(c, 3)] 
            
ans = []

这是获取“ans”输出的公式:

for i in range(len(perm)): 
            
    groups = perm[i] #this is the subset like [2, 4, [3, 1, 5]]

    #flatten the list or returns integer
    clean = [y for x in groups for y in (x if isinstance(x,list) else [x])]

    ans.append(clean)

    print(clean)

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