【问题标题】:Replace one list of items with another list in all possible combinations in python在python中的所有可能组合中用另一个列表替换一个项目列表
【发布时间】:2021-02-10 17:52:17
【问题描述】:

我想在所有可能的组合中用另一个列表替换一个项目列表,而不需要任何重复,例如

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,但结果并不是我想要的,我想知道是否有人知道如何做到这一点,非常感谢你的帮助。 :)

【问题讨论】:

  • @Adamantoisetortoise 我认为他们的问题是如何从输入中生成输出。
  • @hiroprotagonist 不要认为这可以生成最后几个项目,例如让4 在输出序列中排在第一位。

标签: python list replace combinations permutation


【解决方案1】:

这里有一个解决方案:

from itertools import combinations

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

【讨论】:

  • 这永远不会生成例如[5, 2, 3][4, 2, 5]
  • @Masklinn 所以你认为顺序很重要?什么样的订单?
【解决方案2】:

OP 保持 list1 的顺序,并用 list2 中的元素对其进行屏蔽。 我创建了一个 list2 的 powerset,并用 Nones 扩展它以匹配 list1 的长度(= helper)。然后我遍历 helper 的唯一排列,用另一个数组掩蔽一个数组,以隐藏 list1 中掩码包含非无值的部分。

Powerset 来自:How to get all subsets of a set? (powerset)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-18
    • 1970-01-01
    • 2013-08-26
    • 2019-12-24
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多