为了账号安全,请及时绑定邮箱和手机立即绑定

将 python 中所有可能组合中的一个项目列表替换为另一个列表

将 python 中所有可能组合中的一个项目列表替换为另一个列表

MMMHUHU 2024-01-16 15:33:55
我想用所有可能组合中的另一个列表替换一个项目列表,而不进行任何重复,例如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]我已经尝试过 itertools.product 与 zip 但结果并不是我想要的,我想知道是否有人知道如何做到这一点,我真的很感谢你的帮助。:)
查看完整描述

2 回答

?
米琪卡哇伊

TA贡献1998条经验 获得超6个赞

OP 保持 list1 的顺序,并用 list2 中的元素屏蔽它。我创建了 list2 的幂集,并使用 None 对其进行扩展以匹配 list1 (= helper)的长度。然后,我迭代 helper 的唯一排列,用另一个数组掩盖一个数组,以隐藏 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]]



查看完整回答
反对 回复 2024-01-16
?
森林海

TA贡献2011条经验 获得超2个赞

这是一个解决方案:

from itertools import combinations

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


查看完整回答
反对 回复 2024-01-16
  • 2 回答
  • 0 关注
  • 28 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信