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
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.
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.
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.
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')]
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']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With