• 技术文章 >Python技术 >Python基础教程

    如何实现python随机生成数字?

    2020-10-27 17:20:13原创16597
    今天小编就生成随机数,整理了多个方式,方便大家在项目时,根据自己的需求,直接拿来套用即可,以下内容相当详细,具体来看看吧~

    说明:python中生成随机数主要用到random模块,方法主要包括:randint、uniform、random、sample、choice等几种常用方法;

    环境:Mac OS 10.14.6/Windows10、python3.7.3

    1、在[a, b]之间产生随机整数(randint方法)

    代码演示:

    1

    2

    3

    4

    5

    import random; 

      

    for i in range(2):

        ret = random.randint(1000, 9999)

    print("在[a, b]之间产生随机整数:random.randint(1000, 9999)=",ret)

    运行结果:

    2、[a, b]之间产生随机浮点数(uniform方法)

    代码演示:

    1

    2

    3

    4

    5

    import random; 

      

    for i in range(2):

        ret = random.uniform(1.0, 100.0)

    print("在[a, b]之间产生随机浮点数:random.uniform(1.0, 100.0) = ",ret)

    运行结果:

    3、在[0.0, 1.0)之间产生随机浮点数(random方法)

    代码演示:

    1

    2

    3

    4

    5

    6

    7

    import random; 

      

    for i in range(2):

      

       ret = random.random()

      

    print("在[0.0, 1.0)之间产生随机浮点数:random.random() = ",ret)

    运行结果:

    4、在样本samples中随机选择n个(sample方法)

    代码演示:

    1

    2

    3

    4

    5

    6

    import random

      

    samples = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" }

    for i in range(2):

        ret = random.sample(samples, 2)

    print("在样本samples中随机选择n个:random.sample(samples, 2) = ",ret)

    运行结果:

    5、在序列list1中随机选择1个(choice方法)

    代码演示:

    1

    2

    3

    4

    5

    6

    7

    8

    import random

      

      

      

    list1 = ("hello", "world", 'we', 'are', "learning", "python", 'very', 'good')

    for i in range(2):

        ret = random.choice(list1)

    print("在序列list1中随机选择1个:random.choice(list1) =",ret)

    运行结果:

    6、随机生成唯一流水号(时间戳)

    代码演示:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    import datetime; 

    import random; 

      

      

    for i in range (0,1): 

        nowTime=datetime.datetime.now().strftime("%Y%m%d%H%M%S")

        randomNum=random.randint(0,99)

        if randomNum<=10: 

            randomNum=str(0)+str(randomNum) 

        uniqueNum=str(nowTime)+str(randomNum)

    print ("时间戳:",uniqueNum)

    7、随机生成验证码

    代码演示:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    import random

      

    def random_num():

        code = ''

        for i in range(4):

            ran1 = random.randint(0,9)

            ran2 = chr(random.randint(65,90))

            add = random.choice([ran1,ran2])

            code = ''.join([code,str(add)])

        return code

    rand_n = random_num()

    print("验证码:",rand_n)

    运行结果:

    大家可以根据自己的需求,调用上述python模块~如需更多python实用知识,点击进入PyThon学习网教学中心

    专题推荐:python随机生成数字
    上一篇:Python中openpyxl怎样改变字体和颜色 下一篇:Python基础之openpyxl如何实现vlookup函数

    相关文章推荐

    • python开发环境哪个好用?如何搭建?• python正则表达式是什么?怎么用?• python获取当前时间日期有哪些方法?• 怎么用python输出和输入文件及信息?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网