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

    一、random模块

    一、random模块
    import random
    # 大于0且小于1之间的小数
    print(random.random())
    0.42866657593385415
    # 大于等于1且小于等于3之间的整数
    print(random.randint(1, 3))
    3
    # 大于等于1且小于3之间的整数
    print(random.randrange(1, 3))
    2
    # 大于1小于3的小数,如1.927109612082716
    print(random.uniform(1, 3))
    2.1789596280319605
    # 列表内的任意一个元素,即1或者‘23’或者[4,5]
    print(random.choice([1, '23', [4, 5]]))
    [4, 5]
    # random.sample([], n),列表元素任意n个元素的组合,示例n=2
    print(random.sample([1, '23', [4, 5]], 2))
    ['23', 1]
    lis = [1, 3, 5, 7, 9]
    # 打乱l的顺序,相当于"洗牌"
    list1 = ['红桃A', '梅花A', '红桃Q', '方块K']
    random.shuffle(list1)
    print(list1)
    # 默认获取0——1之间任意小数
    res2 = random.random()
    print(res2)
    # 需求: 随机验证码
    '''
    需求: 
        大小写字母、数字组合而成
        组合5位数的随机验证码
        
    前置技术:
        - chr(97)  # 可以将ASCII表中值转换成对应的字符
        # print(chr(101))
        - random.choice
    '''
    
    
    # 获取任意长度的随机验证码
    def get_code(n):
        code = ''
        # 每次循环只从大小写字母、数字中取出一个字符
        # for line in range(5):
        for line in range(n):
    
            # 随机获取一个小写字母
            res1 = random.randint(97, 122)
            lower_str = chr(res1)
    
            # 随机获取一个大写字母
            res2 = random.randint(65, 90)
            upper_str = chr(res2)
    
            # 随机获取一个数字
            number = str(random.randint(0, 9))
    
            code_list = [lower_str, upper_str, number]
    
            random_code = random.choice(code_list)
    
            code += random_code
    
        return code
    
    
    code = get_code(100)
    print(code)
    print(len(code))
  • 相关阅读:
    STM32系列命名规则
    在使用MOS管时要注意的问题
    LED汽车前大灯
    Linux Makefile analysis for plain usr
    Linux Kernel Makefile Test
    linux源码Makefile的详细分析
    "The connection for the USB device '###' was unsuccessful. The device is currently in use"
    Allegro使用技巧
    Integrated Circuit Intro
    ADC/DAC的一些参数
  • 原文地址:https://www.cnblogs.com/lvguchujiu/p/11873885.html
Copyright © 2011-2022 走看看