zoukankan      html  css  js  c++  java
  • python中的随机模块random

    random模块是 python 中为随机数所使用的模块

    ```
    import random

    # 随机生成0-1范围内的随机浮点数
    i = random.random()
    print(i)

    # 随机生成范围内的浮点数
    i = random.uniform(1, 10)
    j = random.uniform(10, 1)
    print(i, j)

    # 随机生成范围内的整数
    i = random.randint(1, 10)
    # j = random.randint(10,1) #随机整数不能倒着来
    print(i)

    # 在范围内随机生成数字
    i = random.randrange(0, 10, 2) # 相当于在[0,2,4,6,8,10]中随机取数字
    print(i)

    # 从一个序列中随机抽取数字
    ls = [1, 3, 4, 5, 6, 7]
    i = random.choice(ls)
    print(i)

    # 打乱一个序列中的元素
    ls = [1, 3, 4, 5, 6, 7]
    random.shuffle(ls)
    print(ls)

    # 随机抽取序列中的元素,凑足函数中要求的个数返回一个新的序列,不改变原序列
    lst = [1, 2, 3, 4, 5]
    print(random.sample(lst, 3))
    print(lst)

    random.seed()
    i = random.random()
    print(i)

    random.seed()
    j = random.random()
    print(j)

    random.seed()
    k = random.random()
    print(k)

    ## seed方法是重置随机数的,不传入参数会按照默认的获取随机数,传入相同参数(参数类型不限)以后会产生相同的随机数
    ```

  • 相关阅读:
    如何为创建大量实例节省内存?
    4-5
    4-6
    4-4
    4-3
    4-2
    3-11
    4-1
    3-10
    3-8
  • 原文地址:https://www.cnblogs.com/Zhao01/p/10083322.html
Copyright © 2011-2022 走看看