numpy.random.shuffle 返回 None

3 投票
4 回答
10306 浏览
提问于 2025-04-18 18:38

我安装了 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,根据它的 文档,它应该是可以正常工作的!我搞不清楚问题出在哪里。

我在 Windows 7 上使用 PyCharm 3.1

4 个回答

1

np.random.shuffle 这个函数不会返回任何东西,它只是直接在原来的数组上进行洗牌。
你可以试试下面的代码:

print np.random.shuffle(a), a

你会发现,在打印数组之前,你已经对数组进行了洗牌。

2

先生,这个输出就是这样。 .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]])
11

如果你想要把东西“打乱”一下,可以使用 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])
10

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]

撰写回答