简体   繁体   English

python中列表子集内的排列

[英]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]所以例如我有这样的列表[1,2,3,4]

I split it into two subsets [1,2], [3,4]我把它分成两个子集[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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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