Chicony Chicony - 1 year ago 67
Python Question

Is there a pythonic way of permuting a list of list?

I have a list of lists containing unique strings and I want to produce an arbitrary number of different ways of sorting it. The list might look like the following:

list = [[a], [b,c], [d], [e,f,g]]

The order of the lists need to be the same but I want to shuffle the ordering within a list and then have them in a single list, e.g

list1 = [a,b,c,d,e,f,g]
list2 = [a,c,b,d,f,e,g]
listN = [a,c,b,d,f,g,e]

What is a good pythonic way of achieving this? I'm on python 2.7.

Answer Source
from itertools import permutations, product

L = [['a'], ['b','c'], ['d'], ['e', 'f', 'g']]

for l in product(*map(lambda l: permutations(l), L)):
    print([item for s in l for item in s])


['a', 'b', 'c', 'd', 'e', 'f', 'g']
['a', 'b', 'c', 'd', 'e', 'g', 'f']
['a', 'b', 'c', 'd', 'f', 'e', 'g']
['a', 'b', 'c', 'd', 'f', 'g', 'e']
['a', 'b', 'c', 'd', 'g', 'e', 'f']
['a', 'b', 'c', 'd', 'g', 'f', 'e']
['a', 'c', 'b', 'd', 'e', 'f', 'g']
['a', 'c', 'b', 'd', 'e', 'g', 'f']
['a', 'c', 'b', 'd', 'f', 'e', 'g']
['a', 'c', 'b', 'd', 'f', 'g', 'e']
['a', 'c', 'b', 'd', 'g', 'e', 'f']
['a', 'c', 'b', 'd', 'g', 'f', 'e']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download