简体   繁体   中英

Permutations inside subsets of a list in python

I have a list and need to get all permutations. But I can do permutations only inside list subsets.

So for example I have list like this [1,2,3,4]

I split it into two subsets [1,2], [3,4]

And I want to get an iterable which will give me

[1,2], [3,4]
[2,1], [3,4]
[1,2], [4,3]
[2,1], [4,3]

So it is equivalent to nested loops. But number of subsets can be different and I cant code it as loops

Try:

from itertools import permutations, product

x,y=[1,2],[3,4]

z=list(product(permutations(x), permutations(y)))

Outputs:

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

you can try with this


import itertools

subset= [1,2,3,4]
for sin itertools.combinations(subset, 2):
        print(s)

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