zoukankan      html  css  js  c++  java
  • 模块之random模块详解

    random模块的使用

    random是Python内置模块, 想要使用该模块, 第一步需要进行导入, 下面介绍几种random常用的函数

    import random
    
    print(random.random())  # 大于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([1, 'a', 'b', 'c', 'd'], 2))  # 列表元素任意2个组合
    
    print(random.uniform(1, 3))  # 大于1小于3的小数
    
    item = [1, 3, 5, 7, 9]
    
    random.shuffle(item)  # 打乱item的顺序, 相当于"洗牌"
    print(item)

    random模块的应用

    对于生成随机验证码, 可以使用random模块进行处理, 具体示例代码如下:

    import random
    
    
    def make_code(size=4):
        res = ''
        for i in range(size):
            s1 = chr(random.randint(65, 90))
            s2 = str(random.randint(0, 9))
            res += random.choice([s1, s2])
    
        return res
    
    
    print(make_code(4))
  • 相关阅读:
    C语言II博客作业03
    C语言II博客作业02
    C语言II博客作业01
    学期总结
    C语言I博客作业08
    C语言I博客作业07
    C语言I博客作业06
    C语言|博客作业05
    C语言I博客作业04
    【lhyaaa】2020深圳大湾区比赛总结
  • 原文地址:https://www.cnblogs.com/featherwit/p/13273594.html
Copyright © 2011-2022 走看看