Skip to content Skip to sidebar Skip to footer

Split A List Into All Pairs In All Possible Ways

I am aware of many posts with the similar questions and have been through all of them. However, I am not able to do what I need. I have list say l1=[0,1,2,3,4] which I want to part

Solution 1:

You can use itertools.permutations and filter out duplicates using frozenset:

In [173]: d = {frozenset([frozenset(x[:2]), frozenset(x[2:4]), x[-1]]) for x in itertools.permutations(l1, 
     ...: len(l1))}

In [174]: d2 = [sorted(x,  key=lambda x: (not isinstance(x, frozenset), x)) for x in d]

In [175]: sorted([[tuple(x[0]), tuple(x[1]), x[-1]] for x in d2])
Out[175]: 
[[(0, 4), (2, 3), 1],
 [(1, 2), (0, 3), 4],
 [(1, 2), (0, 4), 3],
 [(1, 2), (3, 4), 0],
 [(1, 3), (0, 2), 4],
 [(1, 3), (0, 4), 2],
 [(1, 3), (2, 4), 0],
 [(1, 4), (0, 2), 3],
 [(1, 4), (0, 3), 2],
 [(2, 3), (0, 1), 4],
 [(2, 3), (1, 4), 0],
 [(2, 4), (0, 1), 3],
 [(2, 4), (0, 3), 1],
 [(3, 4), (0, 1), 2],
 [(3, 4), (0, 2), 1]]

Solution 2:

You could use itertools.permutations and then use a list comprehension to create pairs out of the first 4 items in each permuation:

l1=[0,1,2,3,4]
from itertools import permutations
l2 = permutations(l1)
l3 = [[(x[0], x[1]), (x[2], x[3]), x[4]]for x in l2]

Solution 3:

[[(0, i), tuple(item for item in l if item not in {0, i ,j}), j] for i in range(1, 5) for j in [item for item in l if item not in {0, i}]]

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

Post a Comment for "Split A List Into All Pairs In All Possible Ways"