假设我有一个值列表
my_list = [1,2,3,4]
我使用 itertools.permutations
来查找此列表的所有组合
perms = itertools.permutations(my_list)
哪个创建
[(1, 2, 3, 4),
(1, 2, 4, 3),
(1, 3, 2, 4),
(1, 3, 4, 2),
(1, 4, 2, 3),
(1, 4, 3, 2),
(2, 1, 3, 4),
(2, 1, 4, 3),
(2, 3, 1, 4),
(2, 3, 4, 1),
(2, 4, 1, 3),
(2, 4, 3, 1),
(3, 1, 2, 4),
(3, 1, 4, 2),
(3, 2, 1, 4),
(3, 2, 4, 1),
(3, 4, 1, 2),
(3, 4, 2, 1),
(4, 1, 2, 3),
(4, 1, 3, 2),
(4, 2, 1, 3),
(4, 2, 3, 1),
(4, 3, 1, 2),
(4, 3, 2, 1)]
我开始遍历它,发现我不再需要 perms
中以 (4,1...
或 (3, 1...
。
我如何重新创建包含这些特定遗漏的列表?迭代和删除项目是不可行的,因为这需要扩展到非常大的尺寸。
编辑:为澄清起见,(4,1,2,3)
应该被删除,因为它以 (4,1...)
开头,但不是 (4,2,1,3)
因为它以 (4,2...)
开头。
最佳答案
>>> from itertools import permutations
>>> my_list = [1,2,3,4]
>>> perms = permutations(my_list)
>>> perms
<itertools.permutations object at 0x107a63ad0>
>>> perms = filter(lambda x: x[:2] != (4,1) and x[:2] != (3,1), perms)
>>> perms
[(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2), (1, 4, 2, 3), (1, 4, 3, 2), (2, 1, 3, 4), (2, 1, 4, 3), (2, 3, 1, 4), (2, 3, 4, 1), (2, 4, 1, 3), (2, 4, 3, 1), (3, 2, 1, 4), (3, 2, 4, 1), (3, 4, 1, 2), (3, 4, 2, 1), (4, 2, 1, 3), (4, 2, 3, 1), (4, 3, 1, 2), (4, 3, 2, 1)]
关于Python - 新的遗漏排列列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30401273/