python 列表子集内的排列
Permutations inside subsets of a list in python
我有一个列表,需要获取所有排列。但是我只能在列表子集中进行排列。
例如我有这样的列表[1,2,3,4]
我把它分成了两个子集
[1,2], [3,4]
我想得到一个可以给我的可迭代对象
[1,2], [3,4]
[2,1], [3,4]
[1,2], [4,3]
[2,1], [4,3]
所以相当于嵌套循环。但是子集的数量可能不同,我不能将其编码为循环
尝试:
from itertools import permutations, product
x,y=[1,2],[3,4]
z=list(product(permutations(x), permutations(y)))
输出:
[((1, 2), (3, 4)), ((1, 2), (4, 3)), ((2, 1), (3, 4)), ((2, 1), (4, 3))]
你可以试试这个
import itertools
subset= [1,2,3,4]
for sin itertools.combinations(subset, 2):
print(s)
我有一个列表,需要获取所有排列。但是我只能在列表子集中进行排列。
例如我有这样的列表[1,2,3,4]
我把它分成了两个子集
[1,2], [3,4]
我想得到一个可以给我的可迭代对象
[1,2], [3,4]
[2,1], [3,4]
[1,2], [4,3]
[2,1], [4,3]
所以相当于嵌套循环。但是子集的数量可能不同,我不能将其编码为循环
尝试:
from itertools import permutations, product
x,y=[1,2],[3,4]
z=list(product(permutations(x), permutations(y)))
输出:
[((1, 2), (3, 4)), ((1, 2), (4, 3)), ((2, 1), (3, 4)), ((2, 1), (4, 3))]
你可以试试这个
import itertools
subset= [1,2,3,4]
for sin itertools.combinations(subset, 2):
print(s)