【问题标题】:numpy.random.shuffle returns Nonenumpy.random.shuffle 返回无
【发布时间】:2014-10-20 08:09:46
【问题描述】:

我安装了numpy1.8.2,然后我尝试了以下代码:

import numpy as np
a = np.arange(10)
print a, np.random.shuffle(a)

但它的输出是:

[0 1 2 3 4 5 6 7 8 9] None

我不知道为什么它返回None,根据它的doc 它应该可以工作!我无法弄清楚问题所在。

我在 Windows 7 上使用 PyCharm 3.1

【问题讨论】:

    标签: python numpy pycharm


    【解决方案1】:

    shuffle 在原地工作,因此不返回值。

    In [1]: x = range(9)
    
    In [2]: x
    Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8]
    
    In [5]: print numpy.random.shuffle(x)
    None
    
    In [6]: x
    Out[6]: [8, 7, 3, 4, 6, 0, 5, 1, 2]
    

    【讨论】:

      【解决方案2】:

      如果您想“洗牌”,请使用np.random.permutation

      例如

      In [1]: import numpy as np
      
      In [2]: np.random.permutation([1,2,3,4,5])
      Out[2]: array([3, 5, 1, 4, 2])
      

      【讨论】:

      • 唯一回答实际潜在问题的帖子
      【解决方案3】:

      先生,它必须这样输出。 .shuffle() 返回 None

      >>> import numpy as np
      >>> print np.random.shuffle.__doc__
      
          shuffle(x)
      
              Modify a sequence in-place by shuffling its contents.
      
              Parameters
              ----------
              x : array_like
                  The array or list to be shuffled.
      
              Returns
              -------
              None
      
              Examples
              --------
              >>> arr = np.arange(10)
              >>> np.random.shuffle(arr)
              >>> arr
              [1 7 5 2 9 4 3 6 0 8]
      
              This function only shuffles the array along the first index of a
              multi-dimensional array:
      
              >>> arr = np.arange(9).reshape((3, 3))
              >>> np.random.shuffle(arr)
              >>> arr
              array([[3, 4, 5],
                     [6, 7, 8],
                     [0, 1, 2]])
      

      【讨论】:

        【解决方案4】:

        np.random.shuffle 不返回任何内容,而是将数组打乱。 请尝试以下方法

        print np.random.shuffle(a), a
        

        当您在打印之前将函数应用于数组时,您会看到数组确实被打乱了。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-01-18
          • 2018-08-11
          • 2018-05-31
          • 2011-01-03
          相关资源
          最近更新 更多