python中的随机模块random

random模块是 python 中为随机数所使用的模块

```
import random

# 随机生成0-1范围内的随机浮点数
i = random.random()
print(i)

# 随机生成范围内的浮点数
i = random.uniform(1, 10)
j = random.uniform(10, 1)
print(i, j)

# 随机生成范围内的整数
i = random.randint(1, 10)
# j = random.randint(10,1) #随机整数不能倒着来
print(i)

# 在范围内随机生成数字
i = random.randrange(0, 10, 2) # 相当于在[0,2,4,6,8,10]中随机取数字
print(i)

# 从一个序列中随机抽取数字
ls = [1, 3, 4, 5, 6, 7]
i = random.choice(ls)
print(i)

# 打乱一个序列中的元素
ls = [1, 3, 4, 5, 6, 7]
random.shuffle(ls)
print(ls)

# 随机抽取序列中的元素,凑足函数中要求的个数返回一个新的序列,不改变原序列
lst = [1, 2, 3, 4, 5]
print(random.sample(lst, 3))
print(lst)

random.seed()
i = random.random()
print(i)

random.seed()
j = random.random()
print(j)

扫描二维码关注公众号,回复: 4409558 查看本文章

random.seed()
k = random.random()
print(k)

## seed方法是重置随机数的,不传入参数会按照默认的获取随机数,传入相同参数(参数类型不限)以后会产生相同的随机数
```

猜你喜欢

转载自www.cnblogs.com/Zhao01/p/10083322.html