• python中random模块的使用


    import random

    random.random() 产生0-1间的随机小数

    >>> res = random.random()
    >>> print(res)
    0.027542593093386247
    >>> res = random.random()
    >>> print(res)
    0.7959514300797362

    random.randint(start_num,end_num)  产生指定起终止值中的随机整数,闭合区间 [start_num,end_num],可取到起终止值

    >>> res = random.randint(1,11)
    >>> print(res)
    9
    >>> res = random.randint(1,11)
    >>> print(res)
    3

    random.randrange(start_num,end_num) 产生指定起终止值中的随机整数,半开区间[start_num,end_num)

    >>> res = random.randrange(1,10)
    >>> print(res)
    5

    random.uniform(start_num,end_num) 产生指定起终止值中的随机小数,全开区间(start_num,end_num)

    >>> res = random.uniform(1,10)
    >>> print(res)
    9.22286461152352
    >>> res = random.uniform(1,10)
    >>> print(res)
    2.7524663134138456
    >>> res = random.uniform(1,10)
    >>> print(res)
    4.339277966397103

    randon.choice(iter) 在单列集合iter中随机选出一个元素

    >>> k = [1,2,"2","name",12]
    >>> res = random.choice(k)
    >>> print(res)
    2
    >>> res = random.choice(k)
    >>> print(res)
    12

    random.sample(iter,n) 在单列集合中随机取出n个元素组成列表返回

    >>> k = [1,2,"2","name",12]
    >>> res = random.sample(k,3)
    >>> print(res)
    [1, '2', 'name']
    >>> res = random.sample(k,3)
    >>> print(res)
    ['2', 12, 'name']

    random.shuffle(iter) 将列表元素顺序打散,不产生新的列表

    >>> print(k)
    [12, 'name', '2', 1, 2]
    >>> res = random.shuffle(k)
    >>> print(k)
    ['2', 'name', 2, 12, 1]
    >>> res = random.shuffle(k)
    >>> print(k)
    [12, 'name', 1, 2, '2']
    >>>

     实例:

    # 产生指定位数的验证码
    import random
    def random_code(count):
        code = ''
        for i in range(count):
            num = random.randint(1, 3)
            if num == 1:
                tag = str(random.randint(0, 9))
            elif num == 2:
                tag = chr(random.randint(65, 90))
            else:
                tag = chr(random.randint(97, 122))
            code += tag
        return code
    print(random_code(6))
  • 相关阅读:
    Design and Implementation of the Sun Network File System
    Flash: An Efficient and Portable Web Server
    Java集合框架练习-计算表达式的值
    后缀数组专题训练
    经典问题-生产者和消费者问题
    ubuntu14.04下配置Java环境以及安装最新版本的eclipse
    Java多线程之CountDownLatch学习
    ZooKeerper学习之Watcher
    ZooKeeper之FastLeaderElection算法详解
    python获取当天日期进行格式转换
  • 原文地址:https://www.cnblogs.com/dongxixi/p/10690038.html
Copyright © 2020-2023  润新知