[英]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
#print(c)
#[2, 4, [3, 1, 5]]
perm = [x for x in itertools.permutations(c, 3)]
ans = []
這是獲得“ans”output 的公式:
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]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.