python 產生隨機函數random

來源:互聯網
上載者:User

標籤:否則   imp   sqrt   隨機函數   bisect   file   get   method   strong   

random是內建(built-in)函數,作用是產生隨機數

匯入模組:

import random 

 

 

接著就可以調用random模組下的函數了使用 dir(random)可以查看random模組下有哪些函數,結果如下:

1 >>> dir(random)  2 [‘BPF‘, ‘LOG4‘, ‘NV_MAGICCONST‘, ‘RECIP_BPF‘, ‘Random‘, ‘SG_MAGICCONST‘, ‘SystemRandom‘, ‘TWOPI‘, ‘_BuiltinMethodType‘, ‘_MethodType‘, ‘_Sequence  3 ‘, ‘_Set‘, ‘__all__‘, ‘__builtins__‘, ‘__cached__‘, ‘__doc__‘, ‘__file__‘, ‘__loader__‘, ‘__name__‘, ‘__package__‘, ‘__spec__‘, ‘_acos‘, ‘_bisect  4 ‘, ‘_ceil‘, ‘_cos‘, ‘_e‘, ‘_exp‘, ‘_inst‘, ‘_itertools‘, ‘_log‘, ‘_pi‘, ‘_random‘, ‘_sha512‘, ‘_sin‘, ‘_sqrt‘, ‘_test‘, ‘_test_generator‘, ‘_urandom‘  5 , ‘_warn‘, ‘betavariate‘, ‘choice‘, ‘choices‘, ‘expovariate‘, ‘gammavariate‘, ‘gauss‘, ‘getrandbits‘, ‘getstate‘, ‘lognormvariate‘, ‘normalvariate‘,   6 ‘paretovariate‘, ‘randint‘, ‘random‘, ‘randrange‘, ‘sample‘, ‘seed‘, ‘setstate‘, ‘shuffle‘, ‘triangular‘, ‘uniform‘, ‘vonmisesvariate‘, ‘weibullvaria  7 te‘] 

 

 

最常用的函數有如下:

 random.randint

1 random.randint(1,10)

語句的含義是產生1至10(包含1與10)的一個隨機數(整數int型)。(參數為整數不可為浮點數否則會報錯)

1 random.randint(20, 10) #該語句是錯誤的。下限必須小於或等於上限  

 

random.random

1 random.random() 

產生一個0到1之間的隨機浮點數,包括0但不包括1,也就是[0.0, 1.0)。

 

random.uniform

1 random.uniform(a, b)

產生a、b之間的隨機浮點數。不過與randint不同的是,a、b可以不是整數,也不用考慮大小。

1  random.uniform(3.65,10.56)#可以這樣
1 random.uniform(10.56, 3.65)#也可以這樣  

 

  

 

random.choice

1 random.choice(seq)

從序列中隨機選取一個元素。seq需要是一個序列,比如list、元組、字串。

1 random.choice([1, 2, 3, 5, 8, 13]) #list  2   3 random.choice(‘hello‘) #字串  4   5 random.choice([‘hello‘, ‘world‘]) #字串組成的list  6   7 random.choice((1, 2, 3)) #元組 

都是可行的用法。

 

random.randrange

1 random.randrange(start, stop, step)

產生一個從start到stop(不包括stop),間隔為step的一個隨機整數。start、stop、step都要為整數,且start<stop。如:

1  random.randrange(0, 21, 2))# 隨機產生0-20之間的偶數

 

 

random.sample

1 random.sample(p, k) 

從p序列中,隨機擷取k個元素,產生一個新序列。sample不改變原來序列。

這個模組很 666,還支援三角、β分布、指數分布、伽馬分布、高斯分布等等非常專業的隨機演算法。

 

random.shuffle

1 random.shuffle(x)  

把序列x中的元素順序打亂。shuffle直接改變原有的序列。如:

1 import random  2 a=[1,2,3,4,5,6]  3 random.shuffle(a)  4 print(a

結果如下:

1 [5, 1, 3, 6, 4, 2]

新手在使用此函數時可能會出現一些錯誤,如下:

1 import random  2 a=[1,2,3,4,5,6]  3 print(random.shuffle(a))  

使用此方法會出現None結果,原因是random.shuffle() 是用來打亂列表元素的,沒有傳回值,所以不能用print(random.shuffle(a))來輸出列印打亂

後的序列

 

python 產生隨機函數random

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.