python中【random】函数用法、randint(a, b)、random( )、uniform(a, b)、shuffle(序列)、sample( )

文章介绍了Python的random模块,包括randint生成闭区间整数,random生成0到1的浮点数,uniform生成指定区间浮点数,shuffle打乱列表,以及sample随机抽取列表片段的功能及其使用示例。

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

1、random.randint(a, b)  —— 随机生成一个整数,范围在[a,b]之间 ——闭区间

即:生成指定范围内的整数。

注意:a、b必须是整数

import random

a = random.randint(1, 3)  # 从1~3里随机生成一个整数,包括1和3
print(a)
# 结果:
1 或者2 或者 3

2、random.random( ) ——随机生成一个浮点数,范围在[0,1)之间 ——左闭右开

import random

a = random.random()
print(a)
# 结果:
0.010555497939993108

3、random.uniform(a, b) ——随机生成一个浮点数,范围在[a,b)之间 ——左闭右开

import random

a = random.uniform(1, 3)
print(a)
# 结果:
1.2921501572960141

4、random.shuffle(x) ——将一个列表中的元素打乱

import random
x = [1, 2, 3, 4, 5]
random.shuffle(x)  # !!!
print(x)

# 结果:
[1, 3, 5, 2, 4]  或者 [2, 1, 4, 5, 3] .....

再比如:利用range( )范围函数,生成列表

x = list(range(10))  # 生成列表:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(x)

# 结果:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


# 现在把它打乱
x = list(range(10))
random.shuffle(x)
print(x)

# 结果:
[4, 5, 9, 2, 8, 7, 1, 3, 0, 6]  

或 [8, 9, 7, 2, 1, 6, 5, 0, 4, 3] ....

5、random.sample(序列, k) ——从指定序列中,随机获取指定长度k的片段

# 例1
import random
x = [1, 3, 2, 5, 6]
a = random.sample(x, 3)
print(a)
# 结果:
[5, 2, 3]

或者[1, 6, 3] ....


# 例2
a = random.sample(range(10), 3)
print(a)
# 结果:
[3, 0, 5]
或者:[8, 6, 5] .....

sample( )函数不会修改原有序列。

import random
x = [1, 3, 2, 5, 6]
a = random.sample(x, 3)
print(a)
print("原来序列:", x)

# 结果:
[2, 5, 6]
原来序列: [1, 3, 2, 5, 6]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值