新聞中心
python中random模塊常見函數(shù):random.choice()、random.randrange()、random.random()、random.seed()、random.shuffle()、random.uniform()。

成都創(chuàng)新互聯(lián)公司服務(wù)項(xiàng)目包括富拉爾基網(wǎng)站建設(shè)、富拉爾基網(wǎng)站制作、富拉爾基網(wǎng)頁制作以及富拉爾基網(wǎng)絡(luò)營銷策劃等。多年來,我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術(shù)優(yōu)勢、行業(yè)經(jīng)驗(yàn)、深度合作伙伴關(guān)系等,向廣大中小型企業(yè)、政府機(jī)構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,富拉爾基網(wǎng)站推廣取得了明顯的社會效益與經(jīng)濟(jì)效益。目前,我們服務(wù)的客戶以成都為中心已經(jīng)輻射到富拉爾基省份的部分城市,未來相信會繼續(xù)擴(kuò)大服務(wù)區(qū)域并繼續(xù)獲得客戶的支持與信任!
1、random.choice()
choice() 方法返回一個(gè)列表,元組或字符串的隨機(jī)項(xiàng)。
實(shí)例:
def gen_code(n): s='er0dfsdfxcvbn7f989fd' code='' for i in range(n): r=random.choice(s) code=code+r return code
2、random.randrange()
randrange() 方法返回指定遞增基數(shù)集合中的一個(gè)隨機(jī)數(shù),基數(shù)缺省值為1。
函數(shù)原型為
random.randrange([start], stop[, step]),
參數(shù)
start – 指定范圍內(nèi)的開始值,包含在范圍內(nèi)。
stop – 指定范圍內(nèi)的結(jié)束值,不包含在范圍內(nèi)。
step – 指定遞增基數(shù),步長。
實(shí)例:使用random.randrange生成指定間隔的字符
import random str1='agdcdfghkjklerop23490' str2=['df','11','88','ff'] r1=random.randrange(0,30,4) r2=random.sample(str1,3) print(r1) print(r2)
3、random.random()
random.random()用于生成一個(gè)0到1的隨機(jī)符點(diǎn)數(shù): 0 <= n < 1.0
實(shí)例:
import random print(random.random()) #0.2852315719761185
4、random.seed()
seed() 方法改變隨機(jī)數(shù)生成器的種子,可以在調(diào)用其他隨機(jī)模塊函數(shù)之前調(diào)用此函數(shù)。
實(shí)例:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import random
print (random.random())
print (random.random())
print ("------- 設(shè)置種子 seed -------")
random.seed( 10 )
print ("Random number with seed 10 : ", random.random())
# 生成同一個(gè)隨機(jī)數(shù)
random.seed( 10 )
print ("Random number with seed 10 : ", random.random())
# 生成同一個(gè)隨機(jī)數(shù)
random.seed( 10 )
print ("Random number with seed 10 : ", random.random())5、random.shuffle()
shuffle() 方法將序列的所有元素隨機(jī)排序,用于打亂有序序列
函數(shù)原型
random.shuffle(x[, random])
實(shí)例:
import random code='' str2=['df','11','88','ff'] random.shuffle(str2) print(str2)
6、random.uniform()
uniform() 方法將隨機(jī)生成下一個(gè)實(shí)數(shù),它在兩個(gè)參數(shù)范圍內(nèi)。
random.uniform(a,b):用于生成一個(gè)指定范圍內(nèi)的隨機(jī)浮點(diǎn)數(shù),兩格參數(shù)中,其中一個(gè)是上限,一個(gè)是下限。如果a>b,則生成的隨機(jī)數(shù)n,即b<=n<=a;如果a>b,則a<=n<=b。
實(shí)例:
>>> import random >>> print random.uniform(10,20) 13.2960134544 >>> print random.uniform(20,10) 15.9038751838
以上就是小編整理的幾種python中random模塊常見函數(shù),希望能對你有所幫助哦~
分享標(biāo)題:創(chuàng)新互聯(lián)Python教程:python中random模塊常見函數(shù)有哪幾種?
URL鏈接:http://fisionsoft.com.cn/article/cdpipec.html


咨詢
建站咨詢
