zoukankan      html  css  js  c++  java
  • python之random函数

     

     1 #-*- coding:utf-8 -*-
     2 
     3 # random各种使用方法
     4 import random
     5  
     6 # 随机生成[0.1)的浮点数
     7 print("random():", random.random())
     8  
     9 # 随机生成1000-9999之间的整数
    10 print("randint(1000, 9999):", random.randint(1000, 9999))
    11  
    12 # 随机生成0-20之间的偶数
    13 print("randrange(0, 21, 2):", random.randrange(0, 21, 2))
    14  
    15 # 随机生成0-20之间的浮点数
    16 print("uniform(0, 20):", random.uniform(0, 20))
    17  
    18 # 从序列中随机选择一个元素
    19 list_string = ['a', 'b', 'c', 'd', 'e']
    20 print("choice(list):", random.choice(list_string))
    21 print("choice(string):", random.choice('abcd'))
    22  
    23 # 对列表元素随机排序
    24 list_number = [1, 2, 3, 4, 5]
    25 random.shuffle(list_number)
    26 print("shuffle(list):", list_number)
    27  
    28 # 从指定序列中随机获取指定长度的片断
    29 print("sample(sequence):", random.sample('abcdefg', 2))

     

    结果:

    random(): 0.39840036736565154
    randint(1000, 9999): 5736
    randrange(0, 21, 2): 2
    uniform(0, 20): 15.785447740011865
    choice(list): b
    choice(string): b
    shuffle(list): [5, 3, 4, 1, 2]
    sample(sequence): ['f', 'b']

    编写一个生成验证码:

     1 import random
     2 def v_code():
     3     code=''
     4     for i in range(5):
     5         code+=str(random.choice([random.randrange(10),chr(random.randrange(65,91))]))
     6        
     7     print(code)
     8      
     9      
    10 v_code()

    结果:

    04TT3

     

  • 相关阅读:
    Dockfile编写常见命令
    coreDNS域名无法解析问题
    开源软件
    容器相关
    日常工具
    持续集成
    mysql主从同步
    生产环境MySQL5.7-my.cnf 配置文件 for linux (转)
    工作交接流程引导图
    文章记录
  • 原文地址:https://www.cnblogs.com/Mengchangxin/p/9256336.html
Copyright © 2011-2022 走看看