洗牌 vs 置换 numpy [英] shuffle vs permute numpy

查看:22
本文介绍了洗牌 vs 置换 numpy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

numpy.random.shuffle(x)numpy.random.permutation(x) 有什么区别?

我已经阅读了文档页面,但是当我只想随机打乱数组的元素时,我无法理解两者之间是否有任何区别.

I have read the doc pages but I could not understand if there was any difference between the two when I just want to randomly shuffle the elements of an array.

更准确地说,假设我有一个数组 x=[1,4,2,8].

To be more precise suppose I have an array x=[1,4,2,8].

如果我想生成x的随机排列,那么shuffle(x)permutation(x)有什么区别?

If I want to generate random permutations of x, then what is the difference between shuffle(x) and permutation(x)?

推荐答案

np.random.permutationnp.random.shuffle 有两个不同点:

np.random.permutation has two differences from np.random.shuffle:

  • 如果传递一个数组,它将返回一个混洗过的数组副本np.random.shuffle 原地打乱数组
  • 如果传递一个整数,它将返回一个混洗的范围,即 np.random.shuffle(np.arange(n))
  • if passed an array, it will return a shuffled copy of the array; np.random.shuffle shuffles the array inplace
  • if passed an integer, it will return a shuffled range i.e. np.random.shuffle(np.arange(n))

如果 x 是一个整数,随机置换 np.arange(x).如果 x 是数组,则复制并随机打乱元素.

If x is an integer, randomly permute np.arange(x). If x is an array, make a copy and shuffle the elements randomly.

源代码可能有助于理解这一点:

The source code might help to understand this:

3280        def permutation(self, object x):
...
3307            if isinstance(x, (int, np.integer)):
3308                arr = np.arange(x)
3309            else:
3310                arr = np.array(x)
3311            self.shuffle(arr)
3312            return arr

这篇关于洗牌 vs 置换 numpy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆