我想创建一个接受两个列表的函数,不保证列表的长度相等,并返回两个列表之间的所有交错。
输入:两个列表的大小不必相等。
输出:保留原始列表顺序的两个列表之间所有可能的交错。
示例: AllInter([1,2],[3,4]) -> [[1,2,3,4], [1,3,2,4], [ 1,3,4,2], [3,1,2,4], [3,1,4,2], [3,4,1,2]]
我不想要解决方案。我想要一个提示。
最佳答案
Itertools 没有足够的能力来处理这个问题,需要对钉子和洞的问题有一些了解
考虑您的示例列表
A = [1, 2] B = [3, 4]
有四个孔 (len(A) + len(B)
),您可以在其中放置元素(钉子)
| || || || |
|___||___||___||___|
在 Python 中,您可以将空插槽表示为 None
slots = [None]*(len(A) + len(B))
将第二个列表中的元素(钉子)放入钉子的方式很简单,就是从孔中选择插槽的方式数
len(A) + len(B)
Clen(B)
= 4
C2
= itertools.combinations(范围(0, len(len(A) + len(B)))
可以描述为
| || || || | Slots
|___||___||___||___| Selected
3 4 (0,1)
3 4 (0,2)
3 4 (0,3)
3 4 (1,2)
3 4 (1,3)
3 4 (2,3)
现在为每个插槽位置填充第二个列表中的元素(钉子)
for splice in combinations(range(0,len(slots)),len(B)):
it_B = iter(B)
for s in splice:
slots[s] = next(it_B)
完成后,您只需要用第一个列表中的元素(钉子)填充剩余的空槽
it_A = iter(A)
slots = [e if e else next(it_A) for e in slots]
在使用另一个插槽位置开始下一次迭代之前,请冲洗孔
slots = [None]*(len(slots))
上述方法的 Python 实现
def slot_combinations(A,B):
slots = [None]*(len(A) + len(B))
for splice in combinations(range(0,len(slots)),len(B)):
it_B = iter(B)
for s in splice:
slots[s] = next(it_B)
it_A = iter(A)
slots = [e if e else next(it_A) for e in slots]
yield slots
slots = [None]*(len(slots))
以及上述实现的 O/P
list(slot_combinations(A,B))
[[3, 4, 1, 2], [3, 1, 4, 2], [3, 1, 2, 4], [1, 3, 4, 2], [1, 3, 2, 4], [1, 2, 3, 4]]
关于python - 如何计算两个列表的所有交错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15306231/