【发布时间】:2016-11-02 22:57:29
【问题描述】:
matlab 的 perms 函数在 numpy 或 scipy 中是否有等效的方法?在 matlab 中,perms 以相反的字典顺序返回输入的所有可能排列的矩阵。
【问题讨论】:
matlab 的 perms 函数在 numpy 或 scipy 中是否有等效的方法?在 matlab 中,perms 以相反的字典顺序返回输入的所有可能排列的矩阵。
【问题讨论】:
Python 有一个名为itertools.permutations 的内置函数。您可以在 python 中的任何iterable 上调用它,它会返回所有全长排列。
【讨论】:
我写了一个更详细的示例,因为我不清楚如何使用第一个答案来实现它:
import numpy as np
import itertools
MyArray = np.arange(3)
permut = itertools.permutations(MyArray)
permut_array = np.empty((0,3))
for p in permut:
permut_array = np.append(permut_array,np.atleast_2d(p),axis=0)
这会返回一个 numpy 排列数组:
>array([[ 0., 1., 2.],
[ 0., 2., 1.],
[ 1., 0., 2.],
[ 1., 2., 0.],
[ 2., 0., 1.],
[ 2., 1., 0.]])
【讨论】:
此实现类似于以前的答案,但它以相反的字典顺序返回数组,以更接近地匹配 MATLAB 的 perms。
import numpy as np
import itertools
def perms(x):
"""Python equivalent of MATLAB perms."""
return np.vstack(list(itertools.permutations(x)))[::-1]
用法:
In [1]: perms(range(3))
Out[1]:
array([[2, 1, 0],
[2, 0, 1],
[1, 2, 0],
[1, 0, 2],
[0, 2, 1],
[0, 1, 2]])
【讨论】: