zoukankan      html  css  js  c++  java
  • Python 使用random模块生成随机数

    需要先导入 random  模块,然后通过 random 静态对象调用该一些方法。

    random() 函数中常见的方法如下:

    复制代码
     1 # coding: utf-8
     2 # Team : Quality Management Center
     3 # Author:Carson
     4 # Date :2019/6/20 17:12
     5 # Tool :PyCharm
     6 
     7 import random
     8 import string
     9 
    10 
    11 print(random.random())                   # 产生 0 到 1 之间的随机浮点数
    12 print(random.randint(1, 10))             # 产生 1 到 10 的一个整数型随机数
    13 print(random.uniform(1, 5))             # 产生  1 到 5 之间的随机浮点数,区间可以不是整数
    14 print(random.choice('tomorrow'))       # 从序列中随机选取一个元素
    15 print(random.choice(['剪刀', '石头', '布'])) # 随机选取字符串
    16 print(random.randrange(1, 100, 2))       # 生成从1到100的间隔为2的随机整数
    17 print(random.sample('zyxwedcba', 5))      # 多个字符中生成指定数量的随机字符
    18 # 从a-zA-Z0-9生成指定数量的随机字符:
    19 ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 8))
    20 print(ran_str)
    21 # 多个字符中选取指定数量的字符组成新字符串:
    22 print ''.join(random.sample(['z','y','x','w','v','u','t','s','r','q','p','o','n','d','c','b','a'], 5))
    23 # 将序列a中的元素顺序打乱
    24 a = [1, 3, 5, 6, 7]
    25 random.shuffle(a)
    26 print(a)
    复制代码

    输出结果如下:

    复制代码
    0.836604144604
    8
    3.57866972595
    r
    石头
    35
    ['d', 'z', 'e', 'b', 'y']
    gT8ByCrp
    tsqao
    [6, 1, 5, 3, 7]
  • 相关阅读:
    混合模式程序集是针对“v2.0.50727”版的运行时生成的,在没有配置其他信息的情况
    静态static与方法重载
    编写的一个“手机”的类
    面向对象编程(OOP)————修饰符
    POJO
    设计模式——单例模式
    矩形类 求面积
    面向对象编程(OOP)————类
    面向对象编程(OOP)
    for、if循环直至输入正确
  • 原文地址:https://www.cnblogs.com/valorchang/p/11398322.html
Copyright © 2011-2022 走看看