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个
posted @ 2019-08-15 19:29  RandySun  阅读(158)  评论(0编辑  收藏  举报