zoukankan      html  css  js  c++  java
  • 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))
  • 相关阅读:
    PHP查看IP时候能ping通
    mysql把查询到不一样的记录插入到另一张表中
    js本地预览图片
    redis 扩展下载
    mysql update select子查询
    mysql view视图的简单使用....
    两表联查关联字段我想查多个怎么办???
    两表联查是关联字段的值位数不一样时怎么办???
    使用PHP生成二维码(PHPQRCode)
    .net初学之SerialPort串口类
  • 原文地址:https://www.cnblogs.com/dongxixi/p/10690038.html
Copyright © 2011-2022 走看看