One - One Code All

Blog Content

numpy之random库简单的随机排列.shuffle(x)、.permutation(x)

Python   2016-08-11 21:09:12

对给定的数组进行重新排列的方式主要有两种:


np.random.shuffle(x) 现场修改序列,改变自身内容。(类似洗牌,打乱顺序)

np.random..permutation(x) 返回一个随机排列


1、np.random.shuffle(x)


#现场修改序列,改变自身内容。(类似洗牌,打乱顺序)

>>> import numpy as np

>>> arr = np.arange(10)

>>> np.random.shuffle(arr)

>>> arr

array([5, 8, 3, 0, 2, 9, 1, 7, 4, 6])



#对多维数组进行打乱排列时,默认是对第一个维度也就是列维度进行随机打乱.


2、permutation(x)


随机排列一个序列,或者返回一个排列的范围。

如果x是一个多维数组,则只会沿着它的第一个索引进行随机排列。

#直接生成一个随机排列的数组


>>> np.random.permutation(10)

array([2, 7, 1, 8, 3, 9, 6, 0, 5, 4])

>>> np.random.permutation([1, 4, 9, 12, 15])

array([15,  1,  9,  4, 12])


#将数组重新排列


两个函数的功能类似,可以在shuffle或者permutation中随机选取调用。



上一篇:MongoDB中ObjectId生成规则参考
下一篇:python全排列combinations和permutations函数

The minute you think of giving up, think of the reason why you held on so long.