ptyhon的random模块

  • random是用于生成随机数的。使用random可以生成随机的数字或者字符.要先import random

生成随机的浮点数

  • random.random()函数用于生成range[0.0,1.0)的随机数
  • random.uniform(a,b)函数用于生成ranger[a,b)的随机数
>>> random.random()
0.32128429914231726
>>> random.uniform(10,20)
10.719934690608408
>>> random.uniform(10,20)
19.000527315499887

生成随机的整数

在实际应用中,可能需要生成随机的整数

  • random.randint(a,b)生成[a,b]之间的整数。其中是可能等于b的。
  • random.randrage([start], stop, [step])在指定范围内,按照指定的step递增,从这个集合中随机生成整数。step默认值为1
  • random.choice(sequence)从序列中随机选择一个元素。sequence可以为list,tuple,字符串等
>>> random.randint(10,20)
17
>>> random.randint(10,20)
11
>>> random.randint(10,20)
20

>>> random.randrange(10,100,4)
86
>>> random.randrange(10,100,4)
42
>>> random.randrange(10,100,4)
86

>>> random.choice(range(10,100,4))
90
>>> random.choice(range(10,100,4))
14
>>> random.choice(range(10,100,4))
86

生成随机的列表

  • random.shuffle(list)将list顺序打乱
  • random.sample(sequence,k)从sequence中选择k个元素,这不会影响sequence.
>>> list=range(1,100)
>>> list
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62,
63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
93, 94, 95, 96, 97, 98, 99]
>>> random.shuffle(list)
>>> list
[6, 96, 19, 72, 5, 94, 27, 73, 53, 41, 55, 2, 23, 3, 32, 30, 1, 31, 90, 50, 60, 24, 7, 44, 40, 71, 87, 37, 29, 34, 13, 7
9, 26, 22, 36, 92, 46, 83, 78, 76, 49, 20, 16, 63, 39, 65, 18, 80, 75, 66, 56, 58, 88, 67, 4, 48, 38, 52, 69, 33, 9, 11,
 99, 93, 17, 70, 10, 35, 86, 97, 61, 59, 42, 45, 85, 91, 84, 14, 47, 8, 77, 89, 95, 15, 68, 62, 25, 74, 28, 12, 54, 98,
81, 64, 51, 82, 21, 43, 57]
>>> random.sample(list, 3)


[6, 19, 12]
>>> random.sample(list, 3)
[15, 94, 96]
>>> random.sample(list, 3)
[89, 84, 87]
>>> random.sample(list, 3)
[7, 53, 22]
>>> random.sample(list, 3)
[62, 54, 75]

你可能感兴趣的:(Random)