gpt4 book ai didi

python - 两个列表的所有可能替换?

转载 作者:太空狗 更新时间:2023-10-30 02:16:20 25 4
gpt4 key购买 nike

(我知道问题的标题可能会产生误导,但我找不到任何其他方式来表述它 - 请随意编辑)

我有两个长度相同的列表:

a = [1,2,3]
b = [4,5,6]

我想用第二个列表获取第一个列表的所有可能替换。

output[0] = [1,2,3] # no replacements
output[1] = [4,2,3] # first item was replaced
output[2] = [1,5,3] # second item was replaced
output[3] = [1,2,6] # third item was replaced
output[4] = [4,5,3] # first and second items were replaced
output[5] = [4,2,6] # first and third items were replaced
output[6] = [1,5,6] # second and third items were replaced
output[7] = [4,5,6] # all items were replaced

请注意,以下问题无法回答此问题:

涉及先前链接答案的可能解决方案是创建多个列表,然后对它们使用 itertools.product 方法。例如,我可以创建 3 个包含 2 个元素的列表,而不是包含 3 个元素的 2 个列表;但是,这会使代码过于复杂,如果可以的话,我宁愿避免这种情况。

有没有简单快捷的方法?

最佳答案

创建 3 个包含两个元素的列表根本不会使代码过于复杂。 zip can "flip the axes" of multiple lists平凡(将 Y 元素的 X 序列变成 X 元素的 Y 序列),使其易于使用 itertools.product:

import itertools

a = [1,2,3]
b = [4,5,6]

# Unpacking result of zip(a, b) means you automatically pass
# (1, 4), (2, 5), (3, 6)
# as the arguments to itertools.product
output = list(itertools.product(*zip(a, b)))

print(*output, sep="\n")

哪些输出:

(1, 2, 3)
(1, 2, 6)
(1, 5, 3)
(1, 5, 6)
(4, 2, 3)
(4, 2, 6)
(4, 5, 3)
(4, 5, 6)

与您的示例输出的顺序不同,但它是同一组可能的替换。

关于python - 两个列表的所有可能替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44593640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com