你真的了解Python的random模块吗?
random模块 用于生成伪随机数 真正意义上的随机数(或者随机事件)在某次产生过程中是按照实验过程中表现的分布概率随机产生的,其结果是不可预测的,是不可见的。而计算机中的随机函数是按照一定算法模拟产生的,其结果是确定的,是可见的。我们可以这样认为这个可预见的结果其出现的概率是100%。所以用计算机随机函数所产生的“随机数”并不随机,是伪随机数。 计算机的伪随机数是由随机种子根据一定的计算方法计算出来的数值。所以,只要计算方法一定,随机种子一定,那么产生的随机数就是固定的。 只要用户或第三方不设置随机种子,那么在默认情况下随机种子来自系统时钟。 Python的这个库在底层使用通用的算法,经过长久的考验,可靠性没得说,但绝对不能用于密码相关的功能。 一、基本方法
二、针对整数的方法
三、针对序列类结构的方法
四、真值分布 random模块最高端的功能其实在这里。
五、可选择的生成器
六、典型的例子 >>> random() # 随机浮点数: 0.0 <= x < 1.0 0.37444887175646646 >>> uniform(2.5,10.0) # 随机浮点数: 2.5 <= x < 10.0 3.1800146073117523 >>> randrange(10) # 0-9的整数: 7 >>> randrange(0,101,2) # 0-100的偶数 26 >>> choice(['win','lose','draw']) # 从序列随机选择一个元素 'draw' >>> deck = 'ace two three four'.split() >>> shuffle(deck) # 对序列进行洗牌,改变原序列 >>> deck ['four','two','ace','three'] >>> sample([10,20,30,40,50],k=4) # 不改变原序列的抽取指定数目样本,并生成新序列 [40,10,50,30] >>> # 6次旋转红黑绿轮盘(带权重可重复的取样),不破坏原序列 >>> choices(['red','black','green'],[18,18,2],k=6) ['red','green','red','black'] >>> # 德州扑克计算概率Deal 20 cards without replacement from a deck of 52 playing cards >>> # and determine the proportion of cards with a ten-value >>> # (a ten,jack,queen,or king). >>> deck = collections.Counter(tens=16,low_cards=36) >>> seen = sample(list(deck.elements()),k=20) >>> seen.count('tens') / 20 0.15 >>> # 模拟概率Estimate the probability of getting 5 or more heads from 7 spins >>> # of a biased coin that settles on heads 60% of the time. >>> trial = lambda: choices('HT',cum_weights=(0.60,1.00),k=7).count('H') >= 5 >>> sum(trial() for i in range(10000)) / 10000 0.4169 >>> # Probability of the median of 5 samples being in middle two quartiles >>> trial = lambda : 2500 <= sorted(choices(range(10000),k=5))[2] < 7500 >>> sum(trial() for i in range(10000)) / 10000 0.7958 下面是生成一个包含大写字母A-Z和数字0-9的随机4位验证码的程序 import random checkcode = '' for i in range(4): current = random.randrange(0,4) if current != i: temp = chr(random.randint(65,90)) else: temp = random.randint(0,9) checkcode += str(temp) print(checkcode) 下面是生成指定长度字母数字随机序列的代码: #!/usr/bin/env python # -*- coding:utf-8 -*- import random,string def gen_random_string(length): # 数字的个数随机产生 num_of_numeric = random.randint(1,length-1) # 剩下的都是字母 num_of_letter = length - num_of_numeric # 随机生成数字 numerics = [random.choice(string.digits) for i in range(num_of_numeric)] # 随机生成字母 letters = [random.choice(string.ascii_letters) for i in range(num_of_letter)] # 结合两者 all_chars = numerics + letters # 洗牌 random.shuffle(all_chars) # 生成最终字符串 result = ''.join([i for i in all_chars]) return result if __name__ == '__main__': print(gen_random_string(64)) 总结 以上就是本文关于你真的了解Python的random模块的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |