亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將一個列表中的元素插入到另一個列表中,生成所有可能的組合

如何將一個列表中的元素插入到另一個列表中,生成所有可能的組合

至尊寶的傳說 2022-06-28 11:07:29
大家好,我需要一些關于 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]...]感謝您的幫助,我希望我能夠正確表達自己。
查看完整描述

2 回答

?
qq_遁去的一_1

TA貢獻1725條經驗 獲得超8個贊

這不是最干凈的方法,但這就是我的意思:


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)


查看完整回答
反對 回復 2022-06-28
?
喵喔喔

TA貢獻1735條經驗 獲得超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]]


查看完整回答
反對 回復 2022-06-28
  • 2 回答
  • 0 關注
  • 167 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號