美文网首页
python random模块

python random模块

作者: 0893051f5f11 | 来源:发表于2018-05-19 10:35 被阅读0次
    1. 随机生成[0.1)的浮点数
      random()
    print("random():", random.random())
    
    1. 随机生成1000-9999之间的整数
      randint(1000, 9999)
    print("randint(1000, 9999):", random.randint(1000, 9999))
    
    1. 随机生成0-20之间的偶数
      randrange(0, 21, 2),返回整型数值
    print("randrange(0, 21, 2):", random.randrange(0, 21, 2))
    
    1. 随机生成0-20之间的浮点数
      uniform(0, 20),返回浮点型数值
    print("uniform(0, 20):", random.uniform(0, 20))
    
    1. 从序列中随机选择一个元素
      choice(list),参数为list
        list_string = ['a', 'b', 'c', 'd', 'e']
        print("choice(list):", random.choice(list_string))
        print("choice(string):", random.choice('abcd'))
    
    1. 对列表元素随机排序
      shuffle(list),参数为list
        list_number = [1, 2, 3, 4, 5]
        random.shuffle(list_number)
        print("shuffle(list):", list_number)
    
    1. 从指定序列中随机获取指定长度的片断
      sample(sequence),必须传入两个参数
    print("sample(sequence):", random.sample('abcdefg', 2))
    

    输出结果:

    random(): 0.3246915361854795
    randint(1000, 9999): 7801
    randrange(0, 21, 2): 16
    uniform(0, 20): 3.0944129126831754
    choice(list): c
    choice(string): c
    shuffle(list): [4, 3, 2, 1, 5]
    sample(sequence): ['d', 'c']
    
    微信关注.png

    相关文章

      网友评论

          本文标题:python random模块

          本文链接:https://www.haomeiwen.com/subject/ultilftx.html