简体   繁体   中英

Permutations on 2D lists (Python)

I have a complex permutation problem that I'm finding really hard to code.

Bear with me, this might look a little ugly.

I have something of this form:

L = [ [[(1, 2)], [(1, 2),(1, 3)]], [[(2, 3)]] ]

I want to output all "permutations" like this:

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

Intuitively, I need all orderings of the tuples contained in the lists (with no repetition). However, tuples within the same list cannot be together. Eg For [[(1, 2)], [(1, 2),(1, 3)]], (1,2) and (1,2),(1,3) are in the same list. So an element in the output cannot be (1,2)(1,3)(1,2).

I have some messy code written that does the job, but will require cleanup of the output:

output=[]
for x in input:
    for y in x:
        a=[]
        for x1 in input:
            if x!=x1:
                for y1 in x1:
                    a.append(list(permutations([y,y1],len([y,y1]))))
        output.append(a)

This would be sufficient, but I also need to be able to do it for inputs like this:

[[[(1, 2)], [(1, 2), (1, 3)]], [[(2, 3)]], [[(4,5),(6,7)]]

Thus, elements like this would be incuded in the output:

[(4,5),(6,7),(1,2),(2,3)]

Anybody have any idea how I should approach this? Or any tips?

I might be wrong, but from what I understand, you want to do the cartesian product of several ensembles (whose element are themselves ensembles) :

[[(1, 2)], [(1, 2),(1, 3)]] X [[(2, 3)]]

Then for each element of this cartesian product, make all the permutations of the elements it contains, in this example, the elements of the cartesian product are :

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

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

And finally take all the permutations of each elements :

permutations of first element : ([(1, 2)],[(2, 3)]), ([(2, 3)],[(1, 2)])

permutations of second element : ([(1, 2),(1, 3)], [(2, 3)]), ([(2, 3)],[(1, 2),(1, 3)])

If this is what you want, then you can do it with product and permutations from the itertools module (you also need chain to properly turn each permutation in a list of tuples and get the exact output you want) :

from itertools import product, permutations, chain
L = [ [[(1, 2)], [(1, 2),(1, 3)]], [[(2, 3)]] ]

for element in product(*L):
    for permutation in permutations(element):
        print(list(chain(*permutation)))



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

You can directly get the list of 'permutations' with list comprehensions :

result = [list(chain(*permutation)) for element in product(*L) for permutation in permutations(element)]
[[(1, 2), (2, 3)],
 [(2, 3), (1, 2)],
 [(1, 2), (1, 3), (2, 3)],
 [(2, 3), (1, 2), (1, 3)]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM