栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python|模块与包——标准模块2(random)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python|模块与包——标准模块2(random)

第五类:random

提供了进行随机选择的工具

整数

import random
print(random.randrange(1,20,7))  #从1开始20结束,步长为7,不包含20 随机产生 1,8,15
15

#随机产生整数
print(random.randint(1,100))   #1到100之间随机数 [1,100] 包含100
for i in range(1,1000):
    print(random.randint(1,100))

import random
x=['猫','狗','兔子','goat'] #序列
print(random.choice(x)) #随机从序列里选出一个元素
goat

import random
y=range(100)  
print(list(y))    #出来一个0-99的列表
z=list(y)
random.shuffle(z)  #打乱列表值
print(z)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
[21, 96, 2, 53, 20, 77, 82, 64, 83, 90, 37, 97, 59, 42, 27, 89, 91, 87, 51, 13, 80, 99, 18, 28, 23, 29, 78, 55, 66, 61, 5, 35, 47, 9, 49, 70, 1, 69, 12, 38, 76, 72, 68, 60, 36, 84, 3, 48, 63, 40, 73, 95, 71, 56, 41, 33, 74, 94, 39, 43, 92, 98, 7, 15, 25, 67, 52, 62, 54, 22, 30, 93, 19, 45, 32, 86, 26, 58, 16, 81, 88, 46, 4, 44, 65, 57, 17, 79, 6, 11, 0, 10, 14, 85, 34, 24, 31, 8, 50, 75]

#x=random.shuffle(z)
#print(x)
#返回值是none,操作对象是list(z的值)

import random
y=['cat','狗','羊羊','兔兔']
z=random.sample(y,4)  #从y里拿4个元素,等于规模值,起到打乱的作用
print(z)

['cat', '羊羊', '狗', '兔兔']
#z=random.sample(y,5)  第二个参数,最大是第一个参数的规模值,不能超过规模值。
Traceback (most recent call last):
  File "C:UsersshiqianLEOAppDataLocalProgramsPythonPython310A.py", line 4, in 
    print(z)
NameError: name 'z' is not defined
import random
print(random.random()) #产生[0,1)之间的随机数
print(random.uniform(9,10)) #产生[9,10)之间的随机数

0.7645722804270685
9.352422658560046
整数序列实数值

randrange(start,stop[,step])

choice(seq)random()
randint(a,b)shuffle(x)uniform(a,b)
sample(population,k)

注意 shuffle() 返回值None

         sample(population,k)  k不能超过规模值,也不能是负数

         uniform(a,b)  可能是[a,b] 也可能是[a,b)  整数与小数存在误差

练习:

编写一个程序:

1.生成一个在100到200之间的随机偶数。

2.将1到100之间的数字随机排序。

(答案在下一节)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1034270.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号