python 生成随机数 random模块

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38165374/article/details/74264545

random模块常用方法

  1. random.random()生成一个随机的浮点数,范围是在0.0~1.0之间。
  2. random.uniform()生成一个随机的浮点数,它可以设定浮点数的范围,一个是上限,一个是下限。
  3. random.randint()随机生一个整数int类型,可以指定这个整数的范围,同样有上限和下限值。
  4. random.choice()可以从任何序列,比如list列表中,选取一个随机的元素返回,可以用于字符串、列表、元组等。
  5. random.shuffle()随机打乱列表中的元素(修改原列表)。
  6. random.sample()可以从指定的序列中,随机的截取指定长度的片断,不作原地修改。

方法演示

1.random.random()

In [38]: random.random()
Out[38]: 0.44287294808701627

2.random.uniform()

In [39]: random.uniform(1,2)
Out[39]: 1.527362656188826

3.random.randint()

In [40]: random.randint(1,10)
Out[40]: 8

4.random.choice()

In [42]: l
Out[42]: [2, 1, 4, 5, 3]

In [43]: random.choice(l)
Out[43]: 2

In [44]: random.choice(l)
Out[44]: 5

5.random.shuffle()

In [46]: l=[1,2,3,4,5,6]

In [47]: random.shuffle(l)

In [48]: l
Out[48]: [5, 1, 4, 3, 6, 2]

6.random.sample()

In [54]: l=[1,2,3,4,5,6]

In [55]:  random.sample(l,2)
Out[55]: [3, 2]

In [56]:  random.sample(l,3)
Out[56]: [1, 6, 2]

In [57]: l
Out[57]: [1, 2, 3, 4, 5, 6]

猜你喜欢

转载自blog.csdn.net/qq_38165374/article/details/74264545