zoukankan      html  css  js  c++  java
  • python random随机数模块

    import random 

    常用方法:

    随即小数:

    random.random()    随机0-1之间的小数

    random.uniform(n,m)  随机n到m之间的小数

    import random
    num = random.random()
    print(num)
    num1 = random.uniform(1,5)
    print(num1)
    

      

    随机整数: ⭐

    random.randint(n,m) 随机n到m之间的整数,包含n和m,顾头又顾尾

    random.randrange(n,m,i) 随机n到m之间的整数,包含n,不包含m,i表示间隔几个取

    import random
    num = random.randint(1,10)
    print(num)
    num1 = random.randrange(1,10,2)
    print(num1)

    随机选择: 

    random.choice(lst)   随机选择一个返回

    random.sample(lst)   随机选择多个返回,返回的个数为函数的第二个参数

    import random
    lst = [1,8,50,41,21,(10,30)]
    num = random.choice(lst)
    print(num)
    #从lst列表中随机取一个元素

    num1 = random.sample(lst,2)
    print(num1)

    打乱顺序  : 

    random.shuffle(lst)

    import random
    lst = [9,5,6,7,2,8,4,3]
    random.shuffle(lst)
    print(lst)

    练习 :

    import random
    def    rand_code(n=6,flags = True):
        st = ""
        for i in range(n):
            num = random.randint(0,9) #随机数字
            if flags :              #if判断用来选择使用纯数字验证码还是数字字母组合的验证码
                letter = chr(random.randint(65,90)) #随机大写字母
                num = random.choice([num,letter])
            st = st + str(num)
        return st
    
    ret = rand_code()    #flags = False的时候走纯数字的验证码,不传值默认True,走数字加字母的验证码
    print(ret)    
    随机验证码

     

  • 相关阅读:
    用Springboot写一个只有一个条件的复杂查询
    Springboot The requested profile "pom.xml" could not be activated because it doesn't not exists
    springboot配置路径
    vuex
    @MappedSuperclass的作用
    icon.css
    default.html
    WebService调用
    通用分页存储过程
    存储过程获得最新订单号
  • 原文地址:https://www.cnblogs.com/beihan/p/9439511.html
Copyright © 2011-2022 走看看