溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python隨機(jī)生成數(shù)組的方法

發(fā)布時(shí)間:2020-07-01 16:42:13 來源:億速云 閱讀:291 作者:清晨 欄目:編程語言

這篇文章主要介紹python隨機(jī)生成數(shù)組的方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

python生成隨機(jī)數(shù)組的方法:

1、使用random模塊生成隨機(jī)數(shù)組

python的random模塊中有一些生成隨機(jī)數(shù)字的方法,例如random.randint, random.random, random.uniform, random.randrange,這些函數(shù)大同小異,均是在返回指定范圍內(nèi)的一個整數(shù)或浮點(diǎn)數(shù),下邊簡單解釋一下這幾個函數(shù)。

(1)random.randint(low, hight) -> 返回一個位于[low,hight]之間的整數(shù)
該函數(shù)接受兩個參數(shù),這兩個參數(shù)必須是整數(shù)(或者小數(shù)位是0的浮點(diǎn)數(shù)),并且第一個參數(shù)必須不大于第二個參數(shù)

>>> import random
>>> random.randint(1,10)
5
>>> random.randint(1.0, 10.0)
5

(2)random.random() -> 不接受參數(shù),返回一個[0.0, 1.0)之間的浮點(diǎn)數(shù)

>>> random.random()
0.9983625479554628

(3)random.uniform(val1, val2) -> 接受兩個數(shù)字參數(shù),返回兩個數(shù)字區(qū)間的一個浮點(diǎn)數(shù),不要求val1小于等于val2

>>> random.uniform(1,5.0)
2.917249424176132
>>> random.uniform(9.9, 2)
3.4288029275359024

生成隨機(jī)數(shù)組
下邊我們用random.randint來生成一個隨機(jī)數(shù)組

import random
def random_int_list(start, stop, length):
  start, stop = (int(start), int(stop)) if start <= stop else (int(stop), int(start))
  length = int(abs(length)) if length else 0
  random_list = []  
  for i in range(length):
   random_list.append(random.randint(start, stop))
  return random_list
接下來我們就可以用這個函數(shù)來生成一個隨機(jī)的整數(shù)序列了   
>>> random_int_list(1,100,10)[54, 13, 6, 89, 87, 39, 60, 2, 63, 61]

2、使用numpy.rando模塊來生成隨機(jī)數(shù)組

(1)np.random.rand 用于生成[0.0, 1.0)之間的隨機(jī)浮點(diǎn)數(shù), 當(dāng)沒有參數(shù)時(shí),返回一個隨機(jī)浮點(diǎn)數(shù),當(dāng)有一個參數(shù)時(shí),返回該參數(shù)長度大小的一維隨機(jī)浮點(diǎn)數(shù)數(shù)組,參數(shù)建議是整數(shù)型,因?yàn)槲磥戆姹镜膎umpy可能不支持非整形參數(shù)。

import numpy as np
>>> np.random.rand(10)
array([ 0.56911206, 0.99777291, 0.18943144, 0.19387287, 0.75090637, 0.18692814, 0.69804514, 0.48808425, 0.79440667, 0.66959075])

(2)np.random.randn該函數(shù)返回一個樣本,具有標(biāo)準(zhǔn)正態(tài)分布。

>>> np.random.randn(10)
array([-1.6765704 , 0.66361856, 0.04029481, 1.19965741, -0.57514593,-0.79603968, 1.52261545, -2.17401814, 0.86671727, -1.17945975])

(3)np.random.shuffle(x) 類似洗牌,打亂順序;np.random.permutation(x)返回一個隨機(jī)排列

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

以上是python隨機(jī)生成數(shù)組的方法的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI