numpy.random.shuffle打乱顺序函数

numpy.random库比Python内置的random库有更多的方法,比如生成随机数组numpy.random.randint(low[,high, size, dtype])。如果不进行科学计算,使用random.randint(a,b)就足够了。
random.shuffle()千万不要用于二维numpy.array(也就是矩阵),正确的姿势当然是使用numpy自带的numpy.random.shuffle()

1、numpy.random. shuffle(x)

shuffle()是不能直接访问的,可以导入numpy.random模块,然后通过 numpy.random 静态对象调用该方法,shuffle直接在原来的数组上进行操作,改变原来数组的顺序,无返回值(是对列表x中的所有元素随机打乱顺序,若x不是列表,则报错)。

import numpy as np
arr = np.arange(10)
np.random.shuffle(arr)
print(arr)
# 输出:[2 4 0 1 8 7 3 6 5 9]

This function only shuffles the array along the first index of a multi-dimensional array,多维矩阵中,只对第一维(行)做打乱顺序操作:

arr = np.arange(9).reshape((3, 3))
np.random.shuffle(arr)
print(arr)
array([[3, 4, 5],
       [6, 7, 8],
       [0, 1, 2]])

2、random.shuffle (x)

shuffle()是不能直接访问的,可以导入 random 模块,然后通过 random 静态对象调用该方法,shuffle直接在原来的数组上进行操作,改变原来数组的顺序,无返回值(是对列表x中的所有元素随机打乱顺序,若x不是列表,则报错)。

import random

x = [20, 16, 10, 5]
random.shuffle(x)
print ("随机排序列表 : ",  x)
随机排序列表 :  [16, 5, 10, 20]

random.shuffle直接作用于多维numpy数组并不会只打乱第一维数据,random.shuffle千万不要用于二维numpy.array(也就是矩阵)

import random
arr = np.arange(9).reshape((3, 3))
print(arr)
# [[0 1 2]
#  [3 4 5]
#  [6 7 8]]
random.shuffle(arr)
print(arr)
# [[0 1 2]
#  [0 1 2]
 # [6 7 8]]

参考1:https://blog.csdn.net/jasonzzj/article/details/53932645
参考2:https://blog.csdn.net/qq_21063873/article/details/80860218

  • 20
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

还能坚持

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值