itertools
确实是你的朋友:
from itertools import permutations
def group(iterable, n=2):
return zip(*([iter(iterable)] * n))
for each in permutations([1, 2, 3, 4, 5, 6]):
print map(list, group(each))
Result:
[[1, 2], [3, 4], [5, 6]]
[[1, 2], [3, 4], [6, 5]]
[[1, 2], [3, 5], [4, 6]]
[[1, 2], [3, 5], [6, 4]]
[[1, 2], [3, 6], [4, 5]]
[[1, 2], [3, 6], [5, 4]]
[[1, 2], [4, 3], [5, 6]]
[[1, 2], [4, 3], [6, 5]]
[[1, 2], [4, 5], [3, 6]]
...
[EDIT]@FrederikNS:在你澄清你的问题之后并自己找到了答案,这是我的解决方案:
from itertools import combinations
def setpartition(iterable, n=2):
iterable = list(iterable)
partitions = combinations(combinations(iterable, r=n), r=len(iterable) / n)
for partition in partitions:
seen = set()
for group in partition:
if seen.intersection(group):
break
seen.update(group)
else:
yield partition
for each in setpartition([1, 2, 3, 4]):
print each
print
for each in setpartition([1, 2, 3, 4, 5, 6]):
print each
Result:
((1, 2), (3, 4))
((1, 3), (2, 4))
((1, 4), (2, 3))
((1, 2), (3, 4), (5, 6))
((1, 2), (3, 5), (4, 6))
((1, 2), (3, 6), (4, 5))
((1, 3), (2, 4), (5, 6))
((1, 3), (2, 5), (4, 6))
((1, 3), (2, 6), (4, 5))
((1, 4), (2, 3), (5, 6))
((1, 4), (2, 5), (3, 6))
((1, 4), (2, 6), (3, 5))
((1, 5), (2, 3), (4, 6))
((1, 5), (2, 4), (3, 6))
((1, 5), (2, 6), (3, 4))
((1, 6), (2, 3), (4, 5))
((1, 6), (2, 4), (3, 5))
((1, 6), (2, 5), (3, 4))