Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a list into pairs in all possible ways

Tags:

python

I have a list (say 6 elements for simplicity)

L = [0, 1, 2, 3, 4, 5] 

and I want to chunk it into pairs in ALL possible ways. I show some configurations:

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

and so on. Here (a, b) = (b, a) and the order of pairs is not important i.e.

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

The total number of such configurations is 1*3*5*...*(N-1) where N is the length of my list.

How can I write a generator in Python that gives me all possible configurations for an arbitrary N?

like image 298
Adam Avatar asked Mar 19 '11 05:03

Adam


People also ask

Can you split a list of lists in Python?

To split a list into n parts in Python, use the numpy. array_split() function. The np. split() function splits the array into multiple sub-arrays.


1 Answers

Take a look at itertools.combinations.

matt@stanley:~$ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)  [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import itertools >>> list(itertools.combinations(range(6), 2)) [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)] 
like image 157
Matt Joiner Avatar answered Sep 21 '22 06:09

Matt Joiner