Python模块 random的简单使用

本文介绍了Python的random模块,包括random.randint()用于生成指定范围内的整数,random.randrange()生成前开后闭的整数序列,random.choice()用于从可迭代对象中随机选取一个元素,random.sample()进行不重复的随机取样,以及random.shuffle()用于打乱列表元素的顺序。示例代码展示了各个函数的用法和注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

random模块,随机数
import random
random.randint() 随机生成数值中间的整数
random.randint(1,3)
返回1或者2 ,是[1,2,3) 是一个前开后闭的随机数
random.randrange() 随机生成数值中间的整数,和range比较,前包后不包
random.randrange(5)
返回值为[0,1,2,3,4,5) 随机值前开后闭的整数
random.choice(iterable) 随机取1个
l29 = [1,2,3,‘abc’]
random.choice(l29)
返回值为列表l29中的随机的一个值
random.sample() 取样,1个值不能取2次,和choice比对
l29 = [1,2,3,‘abc’]
random.sample(l29,2) #返回值为列表l2随机2个
[3, 1]
l29 = [1,2,3,‘abc’]
random.sample(l29,5) #列表l29元素之有4个,如果取样5个则会报错
---------------------------------------------------------------------------ValueError Traceback (most recent call last) in 1 l29 = [1,2,3,‘abc’]----> 2 random.sample(l29,5)c:\users\marc\appdata\local\programs\python\python38\lib\random.py in sample(self, population, k) 361 n = len(population) 362 if not 0 <= k <= n:–> 363 raise ValueError(“Sample larger than population or is negative”) 364 result = [None] * k 365 setsize = 21 # size of a small set minus size of an empty listValueError: Sample larger than population or is negative
random.shuffle() 打乱,重新排列
l29 = [1,2,3,‘abc’]
random.shuffle(l29) #将列表l29重新排列
l29
[‘abc’, 3, 1, 2]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值