Python標準庫--random

[1] 轉載自 http://www.javashuo.com/article/p-uvmxnmtg-w.htmlhtml

從指定範圍內,按指定基數遞增的集合中 ,這篇文章就是對python生成隨機數的應用程序的部分介紹。python

隨機整數:
>>> import random
>>> random.randint(0,99)
21git

隨機選取0到100間的偶數:
>>> import random
>>> random.randrange(0, 101, 2)
42app

隨機浮點數:
>>> import random
>>> random.random() 
0.85415370477785668
>>> random.uniform(1, 10)
5.4221167969800881dom

隨機字符:
>>> import random
>>> random.choice('abcdefg&#%^*f')
'd'ide

多個字符中選取特定數量的字符:
>>> import random
random.sample('abcdefghij',3) 
['a', 'd', 'b']spa

多個字符中選取特定數量的字符組成新字符串:
>>> import random
>>> import string
>>> string.join(random.sample(['a','b','c','d','e','f','g','h','i','j'], 3)).r
eplace(" ","")
'fih'.net

隨機選取字符串:
>>> import random
>>> random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )
'lemon'code

洗牌:
>>> import random
>>> items = [1, 2, 3, 4, 5, 6]
>>> random.shuffle(items)
>>> items
[3, 2, 5, 6, 4, 1]orm

[2] 轉載自https://blog.csdn.net/zheng_lan_fang/article/details/76684761

如下是random模塊的方法:

 

[python]  view plain  copy
 
  1. random.seed(a=None, version=2)  # 初始化僞隨機數生成器。若是未提供a或者a=None,則使用系統時間爲種子。若是a是一個整數,則做爲種子。  
  2.  random.getstate()  # 返回一個當前生成器的內部狀態的對象  
  3.  random.setstate(state)  # 傳入一個先前利用getstate方法得到的狀態對象,使得生成器恢復到這個狀態。  
  4.  random.getrandbits(k)  # 返回range(0,2**k)之間的一個整數,至關於randrange(0,2**k)  
  5.  random.randrange(stop)  # 返回range(0,stop)之間的一個整數  
  6.  random.randrange(start, stop[, step])  # 返回range[start,stop)之間的一個整數,可加step,跟range(0,10,2)相似  
  7.  random.randint(a, b)  # 返回range[a,b]之間的一個整數,等價於然的range(a,b+1)  
  8.  random.choice(seq)  # 從非空序列seq中隨機選取一個元素。若是seq爲空則彈出 IndexError異常。  
  9.  random.choices(population, weights=None, *, cum_weights=None, k=1)  # 3.6版本新增。從population集羣中隨機抽取K個元素(可重複)。weights是相對權重列表,cum_weights是累計權重,兩個參數不能同時存在。  
  10.  random.shuffle(x[, random])  # 隨機打亂序列x內元素的排列順序。只能針對可變的序列,對於不可變序列,請使用下面的sample()方法。  
  11.  random.sample(population, k)  # 從population樣本或集合中隨機抽取K個不重複的元素造成新的序列。經常使用於不重複的隨機抽樣。返回的是一個新的序列,不會破壞原有序列。要從一個整數區間隨機抽取必定數量的整數,請使用sample(range(10000000), k=60)相似的方法,這很是有效和節省空間。若是k大於population的長度,則彈出ValueError異常。  
  12.  random.random()  # 返回一個介於左閉右開[0.0, 1.0)區間的浮點數  
  13.  random.uniform(a, b)  # 返回一個介於a和b之間的浮點數。若是a>b,則是b到a之間的浮點數。這裏的a和b都有可能出如今結果中。  
  14.  random.triangular(low, high, mode)  # 返回一個low <= N <=high的三角形分佈的隨機數。參數mode指明衆數出現位置。  
  15.  random.betavariate(alpha, beta)  # β分佈。返回的結果在0~1之間  
  16.  random.expovariate(lambd)  # 指數分佈  
  17.  random.gammavariate(alpha, beta)  # 伽瑪分佈  
  18.  random.gauss(mu, sigma)  # 高斯分佈  
  19.  random.lognormvariate(mu, sigma)  # 對數正態分佈  
  20.  random.normalvariate(mu, sigma)  # 正態分佈  
  21.  random.vonmisesvariate(mu, kappa)  # 卡帕分佈  
  22.  random.paretovariate(alpha)  # 帕累託分佈  
  23.  random.weibullvariate(alpha, beta)  # 威布爾分佈  


 

實例:

Basic examples:

 
[python]  view plain  copy
 
  1. >>> random()                             # 隨機浮點數:  0.0 <= x < 1.0  
  2. 0.37444887175646646  
  3.   
  4. >>> uniform(2.5, 10.0)                   # 隨機浮點數:  2.5 <= x < 10.0  
  5. 3.1800146073117523  
  6.   
  7.   
  8. >>> randrange(10)                        # 0-9的整數:  
  9. 7  
  10.   
  11. >>> randrange(0, 101, 2)                 # 0-100的偶數  
  12. 26  
  13.   
  14. >>> choice(['win', 'lose', 'draw'])      # 從序列隨機選擇一個元素  
  15. 'draw'  
  16.   
  17. >>> deck = 'ace two three four'.split()  
  18. >>> shuffle(deck)                        # 對序列進行洗牌,改變原序列  
  19. >>> deck  
  20. ['four', 'two', 'ace', 'three']  
  21.   
  22. >>> sample([10, 20, 30, 40, 50], k=4)    # 不改變原序列的抽取指定數目樣本,並生成新序列  
  23. [40, 10, 50, 30]  
  24.   
  25.   
  26. >>> # 6次旋轉紅黑綠輪盤(帶權重可重複的取樣),不破壞原序列,weight[18,18,2]  
  27. >>> choices(['red', 'black', 'green'], [18, 18, 2], k=6)  
  28. ['red', 'green', 'black', 'black', 'red', 'black']  
  29.   
  30. >>> # 德州撲克計算機率Deal 20 cards without replacement from a deck of 52 playing cards  
  31. >>> # and determine the proportion of cards with a ten-value  
  32. >>> # (a ten, jack, queen, or king).  
  33. >>> deck = collections.Counter(tens=16, low_cards=36)  
  34. >>> seen = sample(list(deck.elements()), k=20)  
  35. >>> seen.count('tens') / 20  
  36. 0.15  
  37.   
  38. >>> # 模擬機率Estimate the probability of getting 5 or more heads from 7 spins  
  39. >>> # of a biased coin that settles on heads 60% of the time.'H'的機率是0.6,「T」的機率是1-0.6  
  40. >>> trial = lambda: choices('HT', cum_weights=(0.60, 1.00), k=7).count('H') >= 5  
  41. >>> sum(trial() for i in range(10000)) / 10000  
  42. 0.4169  
  43.   
  44. >>> # Probability of the median of 5 samples being in middle two quartiles  
  45. >>> trial = lambda : 2500 <= sorted(choices(range(10000), k=5))[2]  < 7500  
  46. >>> sum(trial() for i in range(10000)) / 10000  
  47. 0.7958  
  48.   
  49. >>> from statistics import mean  
  50. >>> from random import choices  
  51.   
  52. >>> data = 1, 2, 4, 4, 10  
  53. >>> means = sorted(mean(choices(data, k=5)) for i in range(20))  # mean是求平均  
  54. >>> print(f'The sample mean of {mean(data):.1f} has a 90% confidence '  
  55.       f'interval from {means[1]:.1f} to {means[-2]:.1f}')  # 這裏的f用法  


 

下面是生成一個包含大寫字母A-Z和數字0-9的隨機4位驗證碼的程序

 
[python]  view plain  copy
 
  1. import random  
  2.     
  3. checkcode = ''  
  4. for i in range(4):  
  5.     current = random.randrange(0,4)  
  6.     if current != i:  
  7.         temp = chr(random.randint(65,90))  
  8.     else:  
  9.         temp = random.randint(0,9)  
  10.         checkcode += str(temp)  
  11. print(checkcode)  


 

下面是生成指定長度字母數字隨機序列的代碼:

[python]  view plain  copy
 
  1. import random, string  
  2.   
  3.   
  4. def gen_random_string(length):  
  5.     # 數字的個數隨機產生  
  6.     num_of_numeric = random.randint(1,length-1)  
  7.     # 剩下的都是字母  
  8.     num_of_letter = length - num_of_numeric  
  9.     # 隨機生成數字  
  10.     numerics = [random.choice(string.digits) for i in range(num_of_numeric)]  
  11.     # 隨機生成字母  
  12.     letters = [random.choice(string.ascii_letters) for i in range(num_of_letter)]  
  13.     # 結合二者  
  14.     all_chars = numerics + letters  
  15.     # 洗牌  
  16.     random.shuffle(all_chars)  
  17.     # 生成最終字符串  
  18.     result = ''.join([i for i in all_chars])  
  19.     return result  
  20.   
  21. if __name__ == '__main__':  
  22.     print(gen_random_string(64))  
相關文章
相關標籤/搜索