将列表拆分为所有组合

00_*_*_00 2 python python-itertools

我知道很多帖子都有类似的问题,并且已经浏览过其中很多。但是,我无法做我需要做的事情。

我有列表 L=[0,1,2,3,4,5] 我想将其分成一对元组。例如:

[(0,1,2),(3,4,5)]
[(0,1,3),(2,4,5)]
[(0,1,4),(2,4,5)]
...
Run Code Online (Sandbox Code Playgroud)

每个元组需要包含原始列表中一半的元素(在本例中为 3 个,共 6 个)。解决方案需要使用 3 个元素生成元组的每种组合。

我可以使用以下命令轻松找到列表中所有可能的元组

list(itertools.combinations(L, 3))
Run Code Online (Sandbox Code Playgroud)

[(0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 1, 5), (0, 2, 3), (0, 2, 4), ...]

是否itertools也为此提供任何解决方法?

sch*_*ggl 5

可能有更高效的解决方案可以避免另一半列表的完全额外迭代,但这应该可以忽略不计:

l = [[x, tuple(y for y in L if y not in x)] for x in combinations(L, 3)]
[[(0, 1, 2), (3, 4, 5)],
 [(0, 1, 3), (2, 4, 5)],
 [(0, 1, 4), (2, 3, 5)],
 [(0, 1, 5), (2, 3, 4)],
 [(0, 2, 3), (1, 4, 5)],
 [(0, 2, 4), (1, 3, 5)],
 [(0, 2, 5), (1, 3, 4)],
 [(0, 3, 4), (1, 2, 5)],
 [(0, 3, 5), (1, 2, 4)],
 [(0, 4, 5), (1, 2, 3)],
 [(1, 2, 3), (0, 4, 5)],
 [(1, 2, 4), (0, 3, 5)],
 [(1, 2, 5), (0, 3, 4)],
 [(1, 3, 4), (0, 2, 5)],
 [(1, 3, 5), (0, 2, 4)],
 [(1, 4, 5), (0, 2, 3)],
 [(2, 3, 4), (0, 1, 5)],
 [(2, 3, 5), (0, 1, 4)],
 [(2, 4, 5), (0, 1, 3)],
 [(3, 4, 5), (0, 1, 2)]]
Run Code Online (Sandbox Code Playgroud)

这取决于原始列表中不存在重复项。否则,您将不得不使用索引。以下修改使用相同的方法,但使用组合的列表索引,因此可以处理原始列表中的重复项:

indexes = ((x, (y for y in L if y not in x)) for x in combinations(range(len(L)), 3))
l = [[tuple(L[a] for a in A), tuple(L[b] for b in B)] for A, B in indexes]
Run Code Online (Sandbox Code Playgroud)