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

    random

    random模块很简单,就是生成随机数

    import random
    
    print(random.random())  # 随机生成[0,1)的小数
    print(random.uniform(1, 3))  # 随机生成(1,3)的小数
    print(random.randint(1, 4))  # 随机生成[1,4]的整数
    print(random.randrange(1, 4))  # 随机生成[1,4)的整数
    print(random.randrange(1, 9, 2))  # 随机生成[1,9)的整数,步长为2
    print(random.choice('hello'))  # 从字符串里随机取一个字符
    print(random.choice(["hello", "boy", "gril"]))  # 从列表里随机取一个值
    print(random.sample('abcde', 2))  # 从序列中随机取两个

    结果:

    0.8978876800808587
    2.791243761557495
    2
    1
    7
    l
    gril
    ['d', 'b']

    import random
    
    a = [1, 2, 3, 4, 5, 6]
    random.shuffle(a)  # 将列表打乱,在原列表的基础上打乱顺序
    print(a)

    结果:

    [3, 5, 4, 6, 1, 2]

    生成 5 位随机验证码

    import random
    
    checkcode = ''
    for i in range(5):
        current = random.randrange(0, 5)
        if current == i:
            tmp = chr(random.randint(65, 90))
        else:
            tmp = random.randint(0, 9)
        checkcode += str(tmp)
    print(checkcode)

    结果:

    M79GQ

    import random
    
    for i in range(5):
        # 需要两个参数,第一个是数据源,第二个是在数据源里生成几个
        # 返回的是列表
        num = random.sample('123456asdfg', 5)
        print(num)

    结果:

    ['1', '2', 'a', '5', 'd']
    ['1', '3', 'a', '4', 's']
    ['3', 'g', 'f', '4', '5']
    ['1', '3', '5', '2', '6']
    ['5', 'f', '4', '2', '3']

    import random
    
    for i in range(5):
        # 需要两个参数,第一个是数据源,第二个是在数据源里生成几个
        num = ''.join(random.sample('123456asdfg', 5))
        print(num)

    结果:

    451d3
    as1f6
    g1afs
    12356
    fsd6g
  • 相关阅读:
    iOS加载HTML, CSS代码
    iOS搜索指定字符在字符串中的位置
    【解决方法】You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE)
    刷新指定行或区 cell
    支付宝获取私钥和公钥
    什么是Git?
    第三方库AFNetworking 3.1.0的简单使用
    转:KVC与KVO机制
    转:常用的iOS开源库和第三方组件
    转:setValue和setObject的区别
  • 原文地址:https://www.cnblogs.com/zouzou-busy/p/13702362.html
Copyright © 2011-2022 走看看