Skip to main content
 首页 » 编程设计

python之打乱二维数组

2025年02月15日11oomusou

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

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 函数对二维数组有什么作用? 谢谢,

请您参考如下方法:

检查随机源代码..

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 列表完全执行它..