随机数生成
首先我们需要在程序中引入random》》》import random as r
r.random()用于生成一个随机的浮点数,
>>> print(r.random()) 0.23928059596578843 >>>
r.uniform(10,20),生成一个随机的浮点数,如果a>b 则a为上限,b为下限。如果a<b,则b为上限
>>> print(r.uniform(10,20)) 15.995495884011348 >>> print(r.uniform(20,10)) 13.179092381602349 >>>
#如果没有给定a,b那么会报错
>>> print(r.uniform())
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
print(r.uniform())
TypeError: uniform() missing 2 required positional arguments: ‘a‘ and ‘b‘
>>> print(r.randint())
r.randint(a,b),生成一个随机的整数,a 是下限,b是上限。下限必须小于上限
>>> print(r.randint()) Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> print(r.randint()) TypeError: randint() missing 2 required positional arguments: ‘a‘ and ‘b‘ >>> print(r.randint(1,10)) 1
>>> print(r.randint(10,1))
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
print(r.randint(10,1))
File "D:\python\lib\random.py", line 222, in randint
return self.randrange(a, b+1)
File "D:\python\lib\random.py", line 200, in randrange
raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (10,2, -8)
>>>
r.randrange(a,b,1or2),随机取出指定范围内的奇偶数,1奇数 2偶数
>>> r.randrange(0,10,2) 6 >>> r.randrange(0,10,1) 1 >>> r.randrange(0,10,1) 7 >>>
r.choice(‘qwertuiopolkjhgffdsa‘)所及取出某一个字符
>>> print(r.choice(‘qwertyuiop[]lkjhgfdsazxcvbnm‘)) k >>> print(r.choice(‘qwertyuiop[]lkjhgfdsazxcvbnm‘)) n >>> print(r.choice(‘qwertyuiop[]lkjhgfdsazxcvbnm‘)) t >>>
r.sample(str,num),会随机输出num个字符,且num一定小于等于len(str)
# 小于字符长度时 >>> r.sample(‘qweasd‘,2) [‘d‘, ‘q‘] # 大于字符长度时 >>> r.sample(‘qweasd‘,8) Traceback (most recent call last): File "<pyshell#25>", line 1, in <module> r.sample(‘qweasd‘,8) File "D:\python\lib\random.py", line 319, in sample raise ValueError("Sample larger than population or is negative") ValueError: Sample larger than population or is negative # 等于字符长度时 >>> r.sample(‘qweasd‘,6) [‘s‘, ‘d‘, ‘a‘, ‘e‘, ‘w‘, ‘q‘] >>>
洗牌,也就是随机排序
>>> items = [1,2,3,4,5,6] >>> r.shuffle(items) >>> items [3, 6, 1, 5, 2, 4] >>>