python的random随机数库的用法

  1. random() 方法返回随机生成的一个实数,它在[0,1)范围内。
import random
print(random.random())
0.22942312291053413
  1. randint(m,n)方法返回一个在m和n之间的整数,包括m和n.
import random

print(random.randint(1,10))
5
  1. uniform(m,n)方法返回一个在m和n之间的实数,包括m和n(m和n可以不是整数).
import random

print(random.uniform(1.1,3.4))
1.3462557370289416
  1. seed()函数改变随机数的种子.
  2. randrange(a,b,n)函数生成从a到b的间隔为m的随机整数.
import random

print(random.randrange(1,100,10))
PS E:\vscode-c\build> python -u "e:\vscode-c\build\data_structure\ran.py"
81
PS E:\vscode-c\build> python -u "e:\vscode-c\build\data_structure\ran.py"
51
PS E:\vscode-c\build> python -u "e:\vscode-c\build\data_structure\ran.py"
81
  1. choice(list,dict,str)函数从序列中随机选择一个元素
import random
a = [1,2,3,4]
print(random.choice(a))
3
  1. sample(list,k)函数,从list序列中,随机获取k个元素,生成一个新序列。sample不改变原来序列.
import random
a = [1,2,3,4]
print(random.sample(a,3))
[4, 1, 2]
  1. shuffle()函数,将序列a中的元素顺序打乱.
import random
a = [1,2,3,4]
random.shuffle(a)
print(a)
[2, 1, 4, 3]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cachel wood

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值