第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

將 python 中所有可能組合中的一個項目列表替換為另一個列表

將 python 中所有可能組合中的一個項目列表替換為另一個列表

MMMHUHU 2024-01-16 15:33:55
我想用所有可能組合中的另一個列表替換一個項目列表,而不進行任何重復(fù),例如list1 =[1,2,3] list2 = [4,5]Output =[1,2,3],[1,2,4],[1,2,5],[1,4,3],[1,5,3],[4,2,3],[5,2,3],[1,4,5],[4,2,5],[4,5,3]我已經(jīng)嘗試過 itertools.product 與 zip 但結(jié)果并不是我想要的,我想知道是否有人知道如何做到這一點,我真的很感謝你的幫助。:)
查看完整描述

2 回答

?
米琪卡哇伊

TA貢獻1998條經(jīng)驗 獲得超6個贊

OP 保持 list1 的順序,并用 list2 中的元素屏蔽它。我創(chuàng)建了 list2 的冪集,并使用 None 對其進行擴展以匹配 list1 (= helper)的長度。然后,我迭代 helper 的唯一排列,用另一個數(shù)組掩蓋一個數(shù)組,以隱藏 list1 中掩碼包含非 None 值的部分。

from itertools import chain, combinations, permutations



def powerset(iterable):

    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"

    s = list(iterable)

    return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))



list1 = [1, 2, 3]


list2 = [4, 5]


solutions = []

for s in powerset(list2):

    # for every possibility of list2

    helper = [None] * (len(list1) - len(s))

    helper.extend(s)

    # create something like [None, None, 4]

    for perm in set(permutations(helper, len(helper))):

        # for each permutation of the helper, mask out nones

        solution = []

        for listchar, helperchar in zip(list1, perm):

            if helperchar != None:

                solution.append(helperchar)

            else:

                solution.append(listchar)

        solutions.append(solution)


print(solutions)

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



查看完整回答
反對 回復(fù) 2024-01-16
?
森林海

TA貢獻2011條經(jīng)驗 獲得超2個贊

這是一個解決方案:

from itertools import combinations

output = list(combinations(list1 + list2, 3))


查看完整回答
反對 回復(fù) 2024-01-16
  • 2 回答
  • 0 關(guān)注
  • 173 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號