zoukankan      html  css  js  c++  java
  • 随机数模块 random模块(1)

    1、取随机小数

    import random
    print(random.random())         # (0,1)
    print(random.uniform(2,3))      # (n,m)

    2、取随机整数

    import random
    print(random.randint(1,2))       # [1,2]
    print(random.randrange(1,2))     # [1,2)
    print(random.randrange(1,100,2))     # 取随机奇数

    3、从一个类表中随机抽取

    import random
    lst = [1,2,3,4,5,('a','b'),'ss','dd']
    ret = random.choice(lst)
    print(ret)

    3.2在range中使用

    import random
    ret1 = random.choice(range(100))
    print(ret1)

    3.3在列表中取3个值  

    import random
    lst = [1,2,3,4,5,('a','b'),'ss','dd']
    ret11= random.sample(lst,3)   # sample
    print(ret11)

    4、乱序:元素随机排序

    import random
    lst = [1,2,3,4,5,('a','b'),'ss','dd']
    random.shuffle(lst)
    print(lst)  # ['dd', 3, 1, 4, 5, ('a', 'b'), 2, 'ss']

    5、random的应用   验证码

    import random
    def get_code(n=6):
        code = ''
        for i in range(n):
            num = random.randint(0,9)
            code += str(num)
        return code
    ret = get_code()
    print(ret)

    6、random的应用   带大、小写字母和数字的验证码

    import random
    def get_code(n):
        code = ''
        for i in range(n):
            num = str(random.randint(0,9))
            alpha_upper = chr(random.randint(65,90))
            alpha_lower = chr(random.randint(97,122))
            c = random.choice([num ,alpha_upper,alpha_lower])
            code +=c
        return code
    ret = get_code(6)
    print(ret)
  • 相关阅读:
    C# 读取计算机CPU,HDD信息
    实现多线程下载文件
    安装SharePoint Server的主机重命名
    SharePoint 2010: Change welcome page on PowerShell
    FW: Solving SharePoint Server -503. The service is unavailable, After installation
    XDocument 使用
    ListBox 控件单击事件
    设计Popup Window
    Listbox Binding ItemsSource
    ListBox item Sort
  • 原文地址:https://www.cnblogs.com/youhongliang/p/9585553.html
Copyright © 2011-2022 走看看