【问题标题】:Shuffle 2D array随机播放二维数组
【发布时间】:2017-10-07 22:43:43
【问题描述】:

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

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

【问题讨论】:

  • Shuffle a numpy array的可能重复
  • 问题不是真的重复,但答案确实是there
  • @SergeBallesta:确实,答案就在其中一个答案中,谢谢!

标签: python arrays numpy random shuffle


【解决方案1】:

在检查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]

你看到的最后一行:make the shuffle 失败,因为 numpy 以某种方式执行最后一行部分 ,但 python 列表完全执行它..

【讨论】:

    【解决方案2】:

    random.shuffle 旨在与list 一起使用,而不是array。基本上,当您使用list 和np.random.shuffle 时,您应该使用random.shuffle 和array。

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-04
      • 2015-06-29
      • 1970-01-01
      相关资源
      最近更新 更多