所有可能替换两个列表? [英] All possible replacements of two lists?
问题描述
(我知道问题的标题可能会引起误解,但我找不到其他表达方式-可以随时对其进行编辑)
(I am aware that the title of the question might be misleading, but I could not find any other way to formulate it - feel free to edit it)
我有两个长度相同的列表:
I have two lists, both of the same length:
a = [1,2,3]
b = [4,5,6]
我想用第二个列表替换所有可能的第一个列表.
And I want to obtain all possible replacements of the first list with the second list.
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
请注意,以下问题未回答该问题:
Please note that this question is NOT answered by the following questions:
- How to get all possible combinations of a list’s elements?
- combinations between two lists?
- Python merging two lists with all possible permutations
- All combinations of a list of lists
可能涉及到先前链接的答案的解决方案是创建多个列表,然后对它们使用 itertools.product 方法.例如,我可以创建2个元素的3个列表,而不是2个元素的3个列表.但是,这会使代码过于复杂,如果可以的话,我宁愿避免这种情况.
A possible solution involving the previously linked answers would be to create several lists and then use the itertools.product method on them. For example, instead of having 2 lists of 3 elements, I could create 3 lists of 2 elements; however, that would over-complicate the code and I'd prefer to avoid that if I could.
有一种简便快捷的方法吗?
Is there an easy and quick way to do it?
推荐答案
创建两个元素的3个列表根本不会使代码复杂化. zip
可以翻转"多个列表的轴(将Y元素的X序列转换为X元素的Y序列),从而易于使用itertools.product
:
Creating 3 lists of two elements would not over-complicate the code at all. zip
can "flip the axes" of multiple lists trivially (making X sequences of Y elements into Y sequences of X elements), making it easy to use 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)
与示例输出的排序不同,但是可能的替换集相同.
Different ordering than your example output, but it's the same set of possible replacements.
这篇关于所有可能替换两个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!