zoukankan      html  css  js  c++  java
  • random模块

    random模块

    一、常用方法

    import random
    
    1. 大于0且小于1之间的小数[0,1)

      print(random.random())
      

      0.42866657593385415

    2. 大于等于1且小于等于3之间的整数

      print(random.randint(1, 3))
      

      3

    3. 打乱l的顺序,相当于"洗牌"

      lis = [1, 3, 5, 7, 9]
      
      random.shuffle(lis)
      print(lis)
      

      [9, 1, 5, 7, 3]

    二、不常用方法

    1. 大于等于1且小于3之间的整数

      print(random.randrange(1, 3))
      
    2. 列表内的任意一个元素,即1或者‘23’或者[4,5]

      print(random.choice([1, '23', [4, 5]]))
      
    3. 列表元素任意n个元素的组合,示例n=2

      # random.sample([], n),列表元素任意n个元素的组合,示例n=2
      print(random.sample([1, '23', [4, 5]], 2))
      
    4. 大于1小于3的小数

      print(random.uniform(1, 3))
      

      2.1789596280319605

    三、获取随机数

    import random
    
    
    def random_code(n):
        num_code = ""
    
        while n > 0:
            num = random.randint(48, 122)
            if 57 < num < 65 or 90 < num < 97:
                continue
            num_code += chr(num)
            n -= 1
        return num_code
    
    
    res_code = random_code(5)
    print(res_code)
    
    

    四、总结

    1. random:0-1的随机数
    2. randint:0-100(包含)的整数
    3. shuffle:打乱容器类元素
    4. randrange:1,9之内的整数
    5. uniform:1-3的小数
    6. choice:选一个
    7. sample:选n个
    在当下的阶段,必将由程序员来主导,甚至比以往更甚。
  • 相关阅读:
    CSS盒子模型
    getContextPath、getServletPath、getRequestURI、request.getRealPath的区别
    MYSQL中的CASE WHEN END AS
    单点登录的精华总结
    git&github
    June 21st 2017 Week 25th Wednesday
    June 20th 2017 Week 25th Tuesday
    June 19th 2017 Week 25th Monday
    June 18th 2017 Week 25th Sunday
    June 17th 2017 Week 24th Saturday
  • 原文地址:https://www.cnblogs.com/randysun/p/11360044.html
Copyright © 2011-2022 走看看