python random模块

  1. 随机生成[0.1)的浮点数
    random()
print("random():", random.random())
  1. 随机生成1000-9999之间的整数
    randint(1000, 9999)
print("randint(1000, 9999):", random.randint(1000, 9999))
  1. 随机生成0-20之间的偶数
    randrange(0, 21, 2),返回整型数值
print("randrange(0, 21, 2):", random.randrange(0, 21, 2))
  1. 随机生成0-20之间的浮点数
    uniform(0, 20),返回浮点型数值
print("uniform(0, 20):", random.uniform(0, 20))
  1. 从序列中随机选择一个元素
    choice(list),参数为list
    list_string = ['a', 'b', 'c', 'd', 'e']
    print("choice(list):", random.choice(list_string))
    print("choice(string):", random.choice('abcd'))
  1. 对列表元素随机排序
    shuffle(list),参数为list
    list_number = [1, 2, 3, 4, 5]
    random.shuffle(list_number)
    print("shuffle(list):", list_number)
  1. 从指定序列中随机获取指定长度的片断
    sample(sequence),必须传入两个参数
print("sample(sequence):", random.sample('abcdefg', 2))

输出结果:

random(): 0.3246915361854795
randint(1000, 9999): 7801
randrange(0, 21, 2): 16
uniform(0, 20): 3.0944129126831754
choice(list): c
choice(string): c
shuffle(list): [4, 3, 2, 1, 5]
sample(sequence): ['d', 'c']
微信关注.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Python中的random模块用于生成随机数。下面介绍一下random模块中最常用的几个函数。 random.r...
    随风化作雨阅读 420评论 0 0
  • 代码开始出加入import random导入random模块 1、random.random random.ran...
    marshb阅读 3,625评论 0 1
  • 原文链接 random是用于生成随机数的,我们可以利用它随机生成数字或者选择字符串。 random.random(...
    大明白阅读 752评论 0 51
  • 摘自 http://my.oschina.net/cuffica/blog/33336 random用于生成随机数...
    SateZheng阅读 543评论 0 0
  • random是用于生成随机数的,我们可以利用它随机生成数字或者选择字符串。 random.seed(x)改变随机数...
    一木之夏阅读 149评论 0 0