zoukankan      html  css  js  c++  java
  • python-- random 模块

    random

    random模块很简单,就是生成随机数

    import random
    
    print(random.random())  # 随机生成[0,1)的小数
    print(random.uniform(1, 3))  # 随机生成(1,3)的小数
    print(random.randint(1, 4))  # 随机生成[1,4]的整数
    print(random.randrange(1, 4))  # 随机生成[1,4)的整数
    print(random.randrange(1, 9, 2))  # 随机生成[1,9)的整数,步长为2
    print(random.choice('hello'))  # 从字符串里随机取一个字符
    print(random.choice(["hello", "boy", "gril"]))  # 从列表里随机取一个值
    print(random.sample('abcde', 2))  # 从序列中随机取两个

    结果:

    0.8978876800808587
    2.791243761557495
    2
    1
    7
    l
    gril
    ['d', 'b']

    import random
    
    a = [1, 2, 3, 4, 5, 6]
    random.shuffle(a)  # 将列表打乱,在原列表的基础上打乱顺序
    print(a)

    结果:

    [3, 5, 4, 6, 1, 2]

    生成 5 位随机验证码

    import random
    
    checkcode = ''
    for i in range(5):
        current = random.randrange(0, 5)
        if current == i:
            tmp = chr(random.randint(65, 90))
        else:
            tmp = random.randint(0, 9)
        checkcode += str(tmp)
    print(checkcode)

    结果:

    M79GQ

    import random
    
    for i in range(5):
        # 需要两个参数,第一个是数据源,第二个是在数据源里生成几个
        # 返回的是列表
        num = random.sample('123456asdfg', 5)
        print(num)

    结果:

    ['1', '2', 'a', '5', 'd']
    ['1', '3', 'a', '4', 's']
    ['3', 'g', 'f', '4', '5']
    ['1', '3', '5', '2', '6']
    ['5', 'f', '4', '2', '3']

    import random
    
    for i in range(5):
        # 需要两个参数,第一个是数据源,第二个是在数据源里生成几个
        num = ''.join(random.sample('123456asdfg', 5))
        print(num)

    结果:

    451d3
    as1f6
    g1afs
    12356
    fsd6g
  • 相关阅读:
    MySQL 入门教程
    .net 定时服务
    【搜索面板】规格信息单选
    【搜索面板查询】品牌单选(term过滤查询)
    【搜索框查询】搜索功能+搜索框内容回显
    商品上下架(发布订阅模式)
    Canal广告缓存实现(工作队列模式)
    FastDFS分布式文件系统(适合存储小文件 )
    跨域(浏览器限制本行为)
    购物网站项目
  • 原文地址:https://www.cnblogs.com/zouzou-busy/p/13702362.html
Copyright © 2011-2022 走看看