前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python中random函数的使用方法 详解

python中random函数的使用方法 详解

作者头像
全栈程序员站长
发布2022-07-02 09:32:51
6530
发布2022-07-02 09:32:51
举报

大家好,又见面了,我是你们的朋友全栈君。

代码语言:javascript
复制
# random各种使用方法
import random

# 随机生成[0.1)的浮点数
print("random():", random.random())

# 随机生成1000-9999之间的整数
print("randint(1000, 9999):", random.randint(1000, 9999))

# 随机生成0-20之间的偶数
print("randrange(0, 21, 2):", random.randrange(0, 21, 2))

# 随机生成0-20之间的浮点数
print("uniform(0, 20):", random.uniform(0, 20))

# 从序列中随机选择一个元素
list_string = ['a', 'b', 'c', 'd', 'e']
print("choice(list):", random.choice(list_string))
print("choice(string):", random.choice('abcd'))

# 对列表元素随机排序
list_number = [1, 2, 3, 4, 5]
random.shuffle(list_number)
print("shuffle(list):", list_number)
代码语言:javascript
复制
# 从指定序列中随机获取指定长度的片断
print("sample(sequence):", random.sample('abcdefg', 2))

运行结果如下
代码语言:javascript
复制
random(): 0.6708362810735843
randint(1000, 9999): 5228
randrange(0, 21, 2): 6
uniform(0, 20): 12.767906137387294
choice(list): a
choice(string): d
shuffle(list): [1, 3, 5, 2, 4]
sample(sequence): ['f', 'g']

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/130266.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档