簡體   English   中英

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

[英]Replace one list of items with another list in all possible combinations in python

我想用所有可能的組合中的另一個列表替換一個項目列表,沒有任何重復,例如

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]

我已經嘗試過帶 zip 的 itertools.product 但結果並不是我想要的,我想知道是否有人知道如何做到這一點,我真的很感謝你的幫助。 :)

OP 保持 list1 的順序,並用 list2 中的元素屏蔽它。 我創建了一個 list2 的 powerset,並用 Nones 擴展它以匹配 list1(= helper)的長度。 然后我遍歷 helper 的唯一排列,用另一個數組屏蔽一個數組以隱藏 list1 的部分,其中掩碼包含 not-None 值。

Powerset from: 如何獲取集合的所有子集? (電源組)

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]]

這是一個解決方案:

from itertools import combinations

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM