我在试图解决这个问题时遇到了真正的大脑障碍。我正在尝试编写一个函数,该函数将返回列表的所有排列,并与一些特殊值交错。
函数签名:
def interleaved_permutations(values, num_special_values)
一个例子:
>>> interleaved_permutations([1,2,3,4], 2)
[1,x,x,2,3,4]
[1,x,2,x,3,4]
[1,x,2,3,x,4]
[1,2,x,x,3,4]
...
一个额外的要求是特殊值不能位于列表中的第一个或最后一个。
我知道一定有办法处理一些疯狂的 itertools foo,但我无法想出任何远程接近的方法。我得到的最接近的只是使用 itertools.permutations
我希望比我更Python的人能够提供帮助!
最佳答案
一种方法是使用 itertools.combinations
来选择插入后特殊值的位置:
from itertools import permutations, combinations
def interleaved(values, num_special_values):
width = len(values) + num_special_values
special = 'x'
for perm in permutations(values):
for pos in combinations(range(1, width-1), num_special_values):
it = iter(perm)
yield [special if i in pos else next(it)
for i in range(width)]
这给了我
In [31]: list(interleaved([1,2,3], 2))
Out[31]:
[[1, 'x', 'x', 2, 3],
[1, 'x', 2, 'x', 3],
[1, 2, 'x', 'x', 3],
[...]
[3, 'x', 'x', 2, 1],
[3, 'x', 2, 'x', 1],
[3, 2, 'x', 'x', 1]]
和
In [32]: list(interleaved([1,2,3,4], 2))
Out[32]:
[[1, 'x', 'x', 2, 3, 4],
[1, 'x', 2, 'x', 3, 4],
[1, 'x', 2, 3, 'x', 4],
[...]
[4, 3, 'x', 2, 'x', 1],
[4, 3, 2, 'x', 'x', 1]]
关于python - 与特殊值交织的排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49950769/