Python标准库--random

[1] 转载自 https://www.cnblogs.com/duking1991/p/6121300.html

从指定范围内,按指定基数递增的集合中 ,这篇文章就是对python生成随机数的应用程序的部分介绍。

随机整数:
>>> import random
>>> random.randint(0,99)
21

随机选取0到100间的偶数:
>>> import random
>>> random.randrange(0, 101, 2)
42

随机浮点数:
>>> import random
>>> random.random() 
0.85415370477785668
>>> random.uniform(1, 10)
5.4221167969800881

随机字符:
>>> import random
>>> random.choice('abcdefg&#%^*f')
'd'

多个字符中选取特定数量的字符:
>>> import random
random.sample('abcdefghij',3) 
['a', 'd', 'b']

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

随机选取字符串:
>>> import random
>>> random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )
'lemon'

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

[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))  
posted @ 2018-03-24 09:55  凡心已炽  阅读(426)  评论(0编辑  收藏  举报