Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All possible permutations of a set of lists in Python

In Python I have a list of n lists, each with a variable number of elements. How can I create a single list containing all the possible permutations:

For example

[ [ a, b, c], [d], [e, f] ] 

I want

[ [a, d, e] , [a, d, f], [b, d, e], [b, d, f], [c, d, e], [c, d, f] ] 

Note I don't know n in advance. I thought itertools.product would be the right approach but it requires me to know the number of arguments in advance

like image 551
Ian Davis Avatar asked May 17 '10 22:05

Ian Davis


People also ask

How do you generate all possible combinations of two lists in Python?

The unique combination of two lists in Python can be formed by pairing each element of the first list with the elements of the second list. Method 1 : Using permutation() of itertools package and zip() function. Approach : Import itertools package and initialize list_1 and list_2.

What is Permute in Python?

A permutation, also called an “arrangement number” or “order”, is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. Examples: Input : str = 'ABC' Output : ABC ACB BAC BCA CAB CBA.

How do you find the permutation of a set?

To calculate the number of permutations, take the number of possibilities for each event and then multiply that number by itself X times, where X equals the number of events in the sequence.


2 Answers

You don't need to know n in advance to use itertools.product

>>> import itertools >>> s=[ [ 'a', 'b', 'c'], ['d'], ['e', 'f'] ] >>> list(itertools.product(*s)) [('a', 'd', 'e'), ('a', 'd', 'f'), ('b', 'd', 'e'), ('b', 'd', 'f'), ('c', 'd', 'e'), ('c', 'd', 'f')] 
like image 132
John La Rooy Avatar answered Oct 04 '22 07:10

John La Rooy


You can do it with a multi-level list comprehension:

>>> L1=['a','b','c'] >>> L2=['d'] >>> L3=['e','f'] >>> [[i,j,k] for i in L1 for j in L2 for k in L3] [['a', 'd', 'e'], ['a', 'd', 'f'], ['b', 'd', 'e'], ['b', 'd', 'f'], ['c', 'd', 'e'], ['c', 'd', 'f']] 
like image 25
Daniel DiPaolo Avatar answered Oct 04 '22 08:10

Daniel DiPaolo