python v3.7.0
random是python產(chǎn)生隨機(jī)數(shù)的內(nèi)置庫筹淫,隨機(jī)種子默認(rèn)為系統(tǒng)時(shí)鐘。下面分析模塊中的方法:
random.random()
生成一個(gè)隨機(jī)的浮點(diǎn)數(shù)腔寡,范圍是在[0,1)之間经瓷。
import random
a=random.random()
print(a)
0.4156918860673895
print('{0:.3f}'.format(a))
0.416
print(round(a,3))
0.416
random.uniform(a,b)
random.uniform()方法可以設(shè)定生成的隨機(jī)浮點(diǎn)數(shù)的范圍,兩個(gè)參數(shù)其中一個(gè)是上限液茎,一個(gè)是下限歌殃。如果a > b乔妈,則生成的隨機(jī)數(shù)n: a <= n <= b。如果 a <b氓皱, 則 b <= n <= a路召。
print(random.uniform(1, 1))
1.0
print(random.uniform(1, 2))
1.222097652142283
print(random.uniform(10, 2))
3.2784286513984773
random.randint(start, end)
隨機(jī)生一個(gè)整數(shù)int類型,可以指定這個(gè)整數(shù)的范圍(閉區(qū)間 [start, end])波材,和random.uniform()方法不同股淡,當(dāng)start>end的時(shí)候會(huì)拋出異常。
print(random.randint(1, 1))
1
print(random.randint(1, 2))
2
print(random.randint(2, 1))
ValueError: empty range for randrange() (2,2, 0)
random.choice(seq)
可以從列表廷区,元組或字符串中選取 一個(gè) 隨機(jī)的元素返回唯灵。
print(random.choice([1, 2, 'a']))
2
print(random.choice((3, 4, 5)))
4
print(random.choice("abc"))
c
# 生成指定長度的隨機(jī)字符串
import string
def generate_random_string(k, chars=None):
if chars is None:
chars = string.ascii_letters
else:
for name, seeds in [('[LOWER]', string.ascii_lowercase), ('[UPPER]', string.ascii_uppercase), ('[NUMBER]', string.digits),
('[LETTERS]', string.ascii_letters)]:
chars = chars.replace(name, seeds)
return ''.join([random.choice(chars) for _ in range(k)])
# return ''.join([seeds[random.randint(0, len(chars) - 1)] for _ in range(k)]) # randint是閉區(qū)間,所以需要-1
random.choices(population,weights=None,*,cum_weights=None,k=1)
Python v3.6新增
作用:從集群中隨機(jī)選擇k次數(shù)據(jù)隙轻,支持設(shè)置權(quán)重埠帕,并返回一個(gè)列表。
參數(shù)說明:
- population: 集群
- weights:相對權(quán)重
- cum_weights:累加權(quán)重
- k: 選取次數(shù)
L = [1, 2, 3, 4, 5]
t1 = random.choices(L, k=3)
t2 = random.choices(L, weights=[0, 0, 0, 1, 0], k=3)
print(t1, t2)
>>>
[5, 3, 1] [4, 4, 4]
參數(shù)weights設(shè)置相對權(quán)重玖绿,它的值是一個(gè)列表敛瓷,設(shè)置之后,每一個(gè)成員被抽取到的概率就被確定了斑匪。比如weights=[1,2,3,4,5],那么第一個(gè)成員的概率就是P=1/(1+2+3+4+5)=1/15呐籽。
cum_weights設(shè)置累加權(quán)重,代碼中會(huì)自動(dòng)把相對權(quán)重轉(zhuǎn)換為累加權(quán)重,即如果直接給出累加權(quán)重狡蝶,那么就不需要
給出相對權(quán)重庶橱。比如weights=[1,2,3,4],那么cum_weights=[1,3,6,10]。
random.shuffle(list)
隨機(jī)打亂序列元素的位置贪惹,只能針對可變序列苏章,對于元組等不可變序列會(huì)報(bào)錯(cuò)。要注意馍乙,random.shuffle()會(huì)直接作用于seq本身,而不會(huì)返回任何值,如:
print(random.shuffle([1, 2, 3]))
None
a = [1, 2, 3]
b = a[:]
random.shuffle(b)
print(a, b)
[1, 2, 3] [1, 3, 2]
random.sample(seq,k)
可以從指定的序列(可變or不可變)中垫释,隨機(jī)選取指定長度的片斷丝格,并返回一個(gè)列表,k的取值范圍是 [0,len(seq)]棵譬。
a = "abcdefg"
print(random.sample(a, len(a)))
['c', 'a', 'g', 'b', 'f', 'd', 'e']
b = [1, 2, 3, "ab"]
print(random.sample(a, len(b) - 2))
['d', 'a']
print(random.sample(a, 0))
[ ]
random.send(n=None)
seed( ) 用于指定隨機(jī)數(shù)生成時(shí)所用算法開始的整數(shù)值显蝌。n代表隨機(jī)種子;當(dāng)n=None時(shí)订咸,隨機(jī)種子為系統(tǒng)時(shí)間曼尊,此時(shí)每次生成的隨機(jī)數(shù)因時(shí)間差異而不同,當(dāng)n為其他的數(shù)據(jù)脏嚷,如int骆撇,str等,則以提供的數(shù)據(jù)作為隨機(jī)種子父叙,此時(shí)生成的隨機(jī)數(shù)列固定神郊。
random.seed('test')
print(random.random())
0.6555960613392863
random.seed('test')
print(random.random())
0.6555960613392863