• python中random的一些用法


    #(1)随机小数
    import random
    print(random.random())  #随机大于0 且小于1 之间的小数
    '''
    0.9441832228391154
    '''

    print(random.uniform(0,9))   #随机一个大于0小于9的小数,“0”为下限,“9”是上限
    '''结果:
    1.646583891572416
    '''
     

    #(2)随机整数
    print(random.randint(1,5))  #随机一个大于等于1且小于等于5的整数
    '''结果:
    5
    '''
     

    print random.randint(12,20)      #生成的随机数a: 12 <= a =< 20

    print random.randint(12,20)      #生成的随机数a: 结果永远是20

    print random.randint(12,20)      #该语句是错误的

    print(random.randrange(1,10,2))   #随机一个大于等于1且小于等于10之间的奇数,其中2表示递增基数
    '''结果:
    3
    '''


     

    #(3)随机返回
    print(random.choice(['123','abc',52,[1,2]]))    #随机返回参数列表中任意一个元素
    '''结果:
    abc
    '''

    print(random.sample(['123','abc',52,[1,2]],2))  #随机返回参数列表中任意两个元素,参数二指定返回的数量
    '''结果:
    ['123', 52]
    '''


     

    #(4)打乱列表顺序
    lis = [1,2,5,7,9,10]
    random.shuffle(lis)
    print(lis)
    '''结果:
    [2, 1, 10, 5, 9, 7]
    '''

    (5)验证码生成器

    import random

    def random_num():
        code = ''
        for i in range(4):
            ran1 = random.randint(0,9)
            ran2 = chr(random.randint(65,90))
            add = random.choice([ran1,ran2])
            code = ''.join([code,str(add)])
        return code

    rand_n = random_num()
    print(rand_n)

    随机字符:
    >>> import random
    >>> random.choice('abcdefg&#%^*f')
    'd'

    多个字符中选取特定数量的字符:
    >>> import random
    random.sample('abcdefghij',3) 
    ['a', 'd', 'b']

    多个字符中选取特定数量的字符组成新字符串:
    >>> import random
    >>> import string
    >>> string.join(random.sample(['a','b','c','d','e','f','g','h','i','j'], 3)).r
    eplace(" ","")
    'fih'

    随机选取字符串:
    >>> import random
    >>> random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )
    'lemon'

    洗牌:
    >>> import random
    >>> items = [1, 2, 3, 4, 5, 6]
    >>> random.shuffle(items)
    >>> items
    [3, 2, 5, 6, 4, 1]

  • 相关阅读:
    347. 前 K 个高频元素(桶排序、堆排序)
    322. 零钱兑换 && 416. 分割等和子集(0-1背包问题)
    739. 每日温度 && 503. 下一个更大元素 II (单调栈)
    1110. 删点成林
    个人纪录
    pub get failed (server unavailable) -- attempting retry 1 in 1 second?
    python 遍历文件夹重命名
    flutter vscode 连接iphone失败
    部署以太坊合约
    Web漏洞扫描工具AppScan10介绍
  • 原文地址:https://www.cnblogs.com/Abell/p/12988956.html
Copyright © 2020-2023  润新知