打乱二维数组

Shuffle 2D array

我试图打乱二维数组,但遇到了一些奇怪的行为,可以使用以下代码恢复:

import random
import numpy

a = numpy.array([[1,2,3],[4,5,6],[7,8,9]])
random.shuffle(a)
print 'With rand\n', a

a = numpy.array([[1,2,3],[4,5,6],[7,8,9]])
numpy.random.shuffle(a)
print 'With numpy\n', a

输出

With rand
[[1 2 3]
 [1 2 3]
 [1 2 3]]
With numpy
[[4 5 6]
 [7 8 9]
 [1 2 3]]

如你所见,使用 random 库(我的第一次尝试),它似乎覆盖了元素(或其他东西,我真的不明白这里发生了什么),因此没有执行洗牌. 然而,使用 numpy 库,它工作得很好。

谁能解释一下为什么? IE。这种差异从何而来?如果可能的话,random.shuffle 函数对二维数组有什么作用? 谢谢,

random.shuffle 设计用于 list 而不是 array。基本上,当您使用 array.

时,只要有 listnp.random.shuffle 就应该使用 random.shuffle
a = [[1,2,3],[4,5,6],[7,8,9]]
random.shuffle(a)

b = numpy.array([[1,2,3],[4,5,6],[7,8,9]])
numpy.random.shuffle(b)

检查 random 源代码..

https://svn.python.org/projects/stackless/trunk/Lib/random.py

def shuffle(self, x, random=None, int=int):
    """x, random=random.random -> shuffle list x in place; return None.

    Optional arg random is a 0-argument function returning a random
    float in [0.0, 1.0); by default, the standard random.random.
    """

    if random is None:
        random = self.random
    for i in reversed(xrange(1, len(x))):
        # pick an element in x[:i+1] with which to exchange x[i]
        j = int(random() * (i+1))
        x[i], x[j] = x[j], x[i]

如您所见,最后一行:使 shuffle 失败,因为 numpy 以某种方式执行最后一行 部分 , 但 python 列表完全执行它..