zoukankan      html  css  js  c++  java
  • 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]

  • 相关阅读:
    #define用法详解
    memchr函数
    aiohttp模块1 client
    asyncio标准库7 Producer/consumer
    asyncio标准库6 Threads & Subprocess
    asyncio标准库5 TCP echo client and server
    asyncio标准库4 asyncio performance
    asyncio标准库3 HTTP client example
    asyncio标准库2 Hello Clock
    asyncio标准库1 Hello World
  • 原文地址:https://www.cnblogs.com/Abell/p/12988956.html
Copyright © 2011-2022 走看看