在Python中,求排列可以通过多种方法实现,以下是一些常见的方法:
1. 使用内置的`itertools.permutations`函数:
from itertools import permutations
对于列表[1, 2, 3]
my_list = [1, 2, 3]
获取所有排列
perms = list(permutations(my_list))
print(perms)
输出:
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
2. 使用`itertools.combinations`函数结合列表推导式:
from itertools import combinations
对于列表[1, 2, 3]
my_list = [1, 2, 3]
获取所有排列
perms = [list(p) for p in permutations(my_list)]
print(perms)
输出与上面相同。
3. 使用`numpy`库的`numpy.permute`函数:
import numpy as np
对于列表[1, 2, 3]
my_list = np.array([1, 2, 3])
获取所有排列
perms = np.permute(my_list)
print(perms)
输出:
[array([1, 2, 3]) array([1, 3, 2]) array([2, 1, 3]) array([2, 3, 1])
array([3, 1, 2]) array([3, 2, 1])]
4. 使用`itertools.combinations_with_replacement`函数结合列表推导式:
from itertools import combinations_with_replacement
对于列表[1, 2, 3]
my_list = [1, 2, 3]
获取所有排列
perms = [list(p) for p in permutations(my_list)]
print(perms)
输出与上面相同。
5. 使用`functools.combinations`函数结合列表推导式:
from itertools import combinations
对于列表[1, 2, 3]
my_list = [1, 2, 3]
获取所有排列
perms = [list(p) for p in permutations(my_list)]
print(perms)
输出与上面相同。
6. 使用`itertools.combinations_with_replacement`函数结合列表推导式:
from itertools import combinations_with_replacement
对于列表[1, 2, 3]
my_list = [1, 2, 3]
获取所有排列
perms = [list(p) for p in permutations(my_list)]
print(perms)
输出与上面相同。