# python 生成随机数_python 生成随机数模块random 常用方法总结

random.random()

In [1]: import random

In [2]: random.random()

Out[2]: 0.15790797219589303

randint(a, b)

In [12]: import random

In [13]: random.randint(1,6)

Out[13]: 1

random.uniform(a,b)

In [14]: import random

In [15]: random.uniform(1,6)

Out[15]: 5.497873150216069

choice(seq)

In [16]: import random

In [17]: List = [1,2,3,4,5,6]

In [18]: random.choice(List)

Out[18]: 1

randrange(start, stop[, step = 1])

In [27]: import random

In [28]: random.randrange(1,6)

Out[28]: 3

random.shuffle(x[,random])

In [36]: import random

In [37]: List = [1,2,3,4,5,6]

In [38]: random.shuffle(List)

In [39]: print(List)

[2, 1, 6, 4, 5, 3]

random.sample(sequence,k)

sample，样品，从有序列表中选k个作为一个片段返回。

In [41]: import random

In [42]: List = [1,2,3,4,5,6]

In [43]: random.sample(List,3)

Out[43]: [4, 6, 3]

random.seed ( [x] )

x:改变随机数生成器的种子seed。如果你不了解其原理，你不必特别去设定seed，Python会帮你选择seed。使用同一个种子，每次生成的随机数序列都是相同的。

In [48]: import random

In [49]: random.seed(10)

In [50]: print("Random number with seed 10: ", random.random())

Random number with seed 10: 0.5714025946899135

In [51]: random.seed(10)

In [52]: print("Random number with seed 10: ", random.random())

Random number with seed 10: 0.5714025946899135

In [53]: random.seed(10)

In [54]: print("Random number with seed 10: ", random.random())

Random number with seed 10: 0.5714025946899135

07-13 3万+
05-07 3万+
09-05 7万+
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客