1. 程式人生 > 其它 >numpy.random.shuffle打亂順序函式

numpy.random.shuffle打亂順序函式

技術標籤:Python

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