新聞中心
python生成隨機數(shù)組的方法:

為和田等地區(qū)用戶提供了全套網(wǎng)頁設計制作服務,及和田網(wǎng)站建設行業(yè)解決方案。主營業(yè)務為成都網(wǎng)站設計、成都做網(wǎng)站、和田網(wǎng)站設計,以傳統(tǒng)方式定制建設網(wǎng)站,并提供域名空間備案等一條龍服務,秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務。我們深信只要達到每一位用戶的要求,就會得到認可,從而選擇與我們長期合作。這樣,我們也可以走得更遠!
1、使用random模塊生成隨機數(shù)組
python的random模塊中有一些生成隨機數(shù)字的方法,例如random.randint, random.random, random.uniform, random.randrange,這些函數(shù)大同小異,均是在返回指定范圍內(nèi)的一個整數(shù)或浮點數(shù),下邊簡單解釋一下這幾個函數(shù)。
(1)random.randint(low, hight) -> 返回一個位于[low,hight]之間的整數(shù)
該函數(shù)接受兩個參數(shù),這兩個參數(shù)必須是整數(shù)(或者小數(shù)位是0的浮點數(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)之間的浮點數(shù)
>>> random.random() 0.9983625479554628
(3)random.uniform(val1, val2) -> 接受兩個數(shù)字參數(shù),返回兩個數(shù)字區(qū)間的一個浮點數(shù),不要求val1小于等于val2
>>> random.uniform(1,5.0) 2.917249424176132 >>> random.uniform(9.9, 2) 3.4288029275359024
生成隨機數(shù)組
下邊我們用random.randint來生成一個隨機數(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ù)來生成一個隨機的整數(shù)序列了 >>> random_int_list(1,100,10)[54, 13, 6, 89, 87, 39, 60, 2, 63, 61]
2、使用numpy.rando模塊來生成隨機數(shù)組
(1)np.random.rand 用于生成[0.0, 1.0)之間的隨機浮點數(shù), 當沒有參數(shù)時,返回一個隨機浮點數(shù),當有一個參數(shù)時,返回該參數(shù)長度大小的一維隨機浮點數(shù)數(shù)組,參數(shù)建議是整數(shù)型,因為未來版本的numpy可能不支持非整形參數(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ù)返回一個樣本,具有標準正態(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)返回一個隨機排列
>> 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])
分享名稱:創(chuàng)新互聯(lián)Python教程:python如何隨機生成數(shù)組
本文路徑:http://www.dlmjj.cn/article/dpdhopg.html


咨詢
建站咨詢
