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

    基础

    import random
    
    print(random.random())                          # (1,3)--float 大于0 小于1 的小数
    
    print(random.randint(1,3))                      # [1,3] 开区间 大于等于1 小于等于3 的整数
    
    print(random.randrange(1,3))                    # [1,3) 大于等于1 小于3 的整数
    
    print(random.choice([1,'a',[4,5]]))             # 1 或者 ‘a’ 或者 [4,5]
    
    print(random.sample([111,'aaa','ccc','ddd'],2)) # 列表元素 任意2个组合
    
    print(random.uniform(1,3))                      # 大于1 小于3 的小树
    
    item = [1,3,5,7,9]
    random.shuffle(item)    # 打乱item的顺序,相当于 “洗牌”
    print(item)

    应用:随机验证码

    思路:

    # import random
    # res = ''
    # for i in range(6):
        # 随机字符 = random.choice([从26个小写字母中随机抽取出一个,从10个数字中随机取出一个])
        # 从26个字母中随机抽取出一个 = chr(random.randint(65,90))
        # 从10个数字中随机取出一个 = str(random.randint(0,9))
    
        # 随机字符 = random.choice([从26个字母中随机抽取出一个,从10个数字中随机取出一个])
        # res += 随机字符

    实现代码:

    普通版:4位(大写字母+数字)

    def make_code(size=4):  # 默认长度为4
        import random
        res = ''
        for i in range(size):
            s1 = chr(random.randint(65,90))     # ASCII码表中,65-90是A-Z
            s2 = str(random.randint(0,9))       # 随机整数0-9
    
            res += random.choice([s1,s2])
        return res
    
    print(make_code())

    升级版:6位(+小写字母+大写字母+数字)

    def make_code_plus(size=6):  # 默认长度为6
        import random
        res = ''
        for i in range(size):
            s1 = chr(random.randint(65,90))     # ASCII码表中,65-90是A-Z
            s2 = chr(random.randint(97,122))     # ASCII码表中,97-122是a-z
            s3 = str(random.randint(0,9))       # 随机整数0-9
    
            res += random.choice([s1,s2,s3])
        return res
    
    print(make_code_plus())

    思维导图(点击链接

  • 相关阅读:
    make menuconfig出错需要安装文件
    编译内核,配置内核make menuconfig
    busbox编译出错,arm-linux-未找到命令
    screen命令
    Shell系列
    ExtJS清除表格缓存
    ExtJS发送POST请求 参数格式为JSON
    ExtJS实现分页grid paging
    ExtJS错误解决 Cannot read property 'on' of undefined
    解决com.mongodb.MongoException$CursorNotFound: cursor 0 not found on server
  • 原文地址:https://www.cnblogs.com/zhww/p/12984014.html
Copyright © 2011-2022 走看看