random模块,随机数 import random random.randint() 随机生成数值中间的整数 random.randint(1,3) 返回1或者2 ,是[1,2,3) 是一个前开后闭的随机数 random.randrange() 随机生成数值中间的整数,和range比较,前包后不包 random.randrange(5) 返回值为[0,1,2,3,4,5) 随机值前开后闭的整数 random.choice(iterable) 随机取1个 l29 = [1,2,3,‘abc’] random.choice(l29) 返回值为列表l29中的随机的一个值 random.sample() 取样,1个值不能取2次,和choice比对 l29 = [1,2,3,‘abc’] random.sample(l29,2) #返回值为列表l2随机2个 [3, 1] l29 = [1,2,3,‘abc’] random.sample(l29,5) #列表l29元素之有4个,如果取样5个则会报错 ---------------------------------------------------------------------------ValueError Traceback (most recent call last) in 1 l29 = [1,2,3,‘abc’]----> 2 random.sample(l29,5)c:\users\marc\appdata\local\programs\python\python38\lib\random.py in sample(self, population, k) 361 n = len(population) 362 if not 0 <= k <= n:–> 363 raise ValueError(“Sample larger than population or is negative”) 364 result = [None] * k 365 setsize = 21 # size of a small set minus size of an empty listValueError: Sample larger than population or is negative random.shuffle() 打乱,重新排列 l29 = [1,2,3,‘abc’] random.shuffle(l29) #将列表l29重新排列 l29 [‘abc’, 3, 1, 2]
|