简体   繁体   English

将列表分成所有组合

[英]Splitting a list into all combinations

I am aware of many posts with the similar questions and have been through many of them. 我知道有很多问题类似的帖子,并且已经解决了很多问题。 However, I am not able to do what I need. 但是,我无能为力。

I have list L=[0,1,2,3,4,5] which I want to split into a pair of tuples. 我有列表L = [0,1,2,3,4,5]我想将其拆分为一对元组。 For example: 例如:

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

Each tuple needs to contain half of the elements from the original list (in this example 3 of 6). 每个元组都需要包含原始列表中一半的元素(在此示例中为3之6)。 A solution needs to produce every combination of tuples using 3 elements. 一个解决方案需要使用3个元素来生成元组的每种组合。

I can easily find all the possible tuple within the list using 我可以使用以下命令轻松找到列表中所有可能的元组

list(itertools.combinations(L, 3))

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

Does itertools offers any workround for this as well? itertools是否也为此提供任何工作环境?

There may be more performant solutions that avoid a complete extra iteration of the list for the other half, but that should be rather negligible: 可能会有更多性能更好的解决方案避免对列表的另一半进行完整的额外迭代,但这应该可以忽略不计:

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)]]

This depends on the absence of duplicates in the original list. 这取决于原始列表中是否没有重复项。 Otherwise you'd have to work with the indexes instead. 否则,您将不得不使用索引。 The following modification uses the same approach, but uses the list indexes for the combinations and can thus handle duplicates in the original list: 以下修改使用相同的方法,但是将列表索引用于组合,因此可以处理原始列表中的重复项:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM