小编典典

所有可能替换两个列表?

python

(我知道该问题的标题可能会误导您,但我找不到其他表达方式-随时进行编辑)

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

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
方法。例如,我可以创建2个元素的3个列表,而不是2个元素的3个列表。但是,这会使代码过于复杂,如果可以的话,我宁愿避免这种情况。

有一种简单快捷的方法吗?


阅读 190

收藏
2020-12-20

共1个答案

小编典典

创建两个元素的3个列表根本不会使代码复杂化。zip可以轻松地“翻转”多个列表的轴(将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)

与示例输出的排序不同,但是可能的替换集相同。

2020-12-20