随机数搞不明白?不存在的!

python随机数

Python定义了一组用于生成或操作随机数的函数。这种特殊类型的函数用于许多游戏、彩票或任何需要生成随机数的应用程序。

随机数的操作

1、choice(): 这个函数用于在容器中生成一个随机数

2、randrange(beg,end,step):这个函数用来在给定的参数中生成随机数。这个函数接收三个参数,起始值,结束值,略过值。

下面看示例代码:

#导入'random'模块,进行随机操作
import random

#使用choice(),从给出的列表中随机选取一个数值

print('A random number from list is :',end='')
print(random.choice([1,2,3,4,5,6,7]))


#使用randrange()函数生成一个给定范围内的随机数。

print('A random number from range is :',end='')
print(random.randrange(20,50,3))

3、random():用来生成一个小于1,大于或等于0的随机浮点数

4、seed():这个函数映射一个特定的随机数和前面提到的seed参数。在种子值之后调用的所有随机数都返回映射的数字。

import random
#输出浮点数
print ("A random number between 0 and 1 is : ", end="") 
print (random.random()) 
  
#使用seed()生成一个随机种子 
random.seed(5) 
  
# 打印映射的随机数
print ("The mapped random number with 5 is : ", end="") 
print (random.random()) 
  
# 生成另外一个随机种子
random.seed(7) 
  
print ("The mapped random number with 7 is : ", end="") 
print (random.random()) 
  
#再一次用5作为参数
random.seed(5) 
  

print ("The mapped random number with 5 is : ",end="") 
print (random.random()) 
  
#再一次用7作为参数 
random.seed(7) 
  

print ("The mapped random number with 7 is : ",end="") 
print (random.random()) 

输出:

A random number between 0 and 1 is : 0.510721762520941
The mapped random number with 5 is : 0.6229016948897019
The mapped random number with 7 is : 0.32383276483316237
The mapped random number with 5 is : 0.6229016948897019
The mapped random number with 7 is : 0.32383276483316237

5、shuffle():用来将整个列表中的数值打乱,重新排列。

6、uniform(a,b):用来生成给定范围的浮点数

import random 

# 初始化列表 
li = [1, 4, 5, 10, 2] 
  
# 打印重排之前的list 
print ("The list before shuffling is : ", end="") 
for i in range(0, len(li)): 
    print (li[i], end=" ") 
print("\r") 
  
# 重拍 
random.shuffle(li) 
  
# 打印重排之后的list
print ("The list after shuffling is : ", end="") 
for i in range(0, len(li)): 
    print (li[i], end=" ") 
print("\r") 

#使用uniform()生成给定范围内的浮点数
print ("The random floating point number between 5 and 10 is : ",end="") 
print (random.uniform(5,10)) 

输出:

The list before shuffling is : 1 4 5 10 2 

The list after shuffling is : 10 1 4 2 5 

The random floating point number between 5 and 10 is : 5.923955296706723
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 14,330评论 0 38
  • 1. 4月25日,周成来电。 他在电话那头兴奋不已,连话都快说不清。 “丫头,丫头,哈哈,丫头!” “怎么了,你倒...
    Miss小泥鳅阅读 9,916评论 307 221
  • 星期二,天气炎热 梦想三周岁 今天我和姐姐偷偷去啤酒节了,妹妹很聪明,她早就从我们的交头接耳猜到我们去玩了,回来后...
    饺子的功力阅读 152评论 0 0
  • 该去洗澡了,可她站在沙发背上不下来,说沙发上有渣渣脚不愿踩在上面。僵持很久,看着她她眼睛里含着眼泪又不哭出来的倔强...
    我是我亦非我阅读 840评论 0 1
  • 凝视那一盆墨绿的君子兰,它如同一位稳重的青年,时而低头沉思,时而迎风飘动,在那棕色花盆的衬托下越发的青翠欲滴,走上...
    32号葛睿阅读 173评论 0 0

友情链接更多精彩内容