【问题标题】:Python equivalent for matlab's permsPython 等价于 matlab 的烫发
【发布时间】:2016-11-02 22:57:29
【问题描述】:

matlab 的 perms 函数在 numpy 或 scipy 中是否有等效的方法?在 matlab 中,perms 以相反的字典顺序返回输入的所有可能排列的矩阵。

【问题讨论】:

    标签: python matlab numpy scipy


    【解决方案1】:

    Python 有一个名为itertools.permutations 的内置函数。您可以在 python 中的任何iterable 上调用它,它会返回所有全长排列。

    【讨论】:

      【解决方案2】:

      我写了一个更详细的示例,因为我不清楚如何使用第一个答案来实现它:

      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.]])
      

      【讨论】:

        【解决方案3】:

        此实现类似于以前的答案,但它以相反的字典顺序返回数组,以更接近地匹配 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]])
        

        【讨论】:

          猜你喜欢
          • 2021-08-07
          • 2012-10-18
          • 2022-11-02
          • 1970-01-01
          • 1970-01-01
          • 2014-10-17
          • 2021-11-25
          • 2014-09-07
          • 1970-01-01
          相关资源
          最近更新 更多