random模块是产生随机数的模块
1、random.random()
这是产生0~1之间一个随机浮点数,但是不会包括1
import random num = 0 while num < 10: print(random.random(),'\t',end='') num += 1 if num % 5 == 0: print()
0.5498432689828007 0.3831223570880221 0.9274241638226295 0.8374157068420778 0.17528783212413213 0.5786066256544846 0.48102842322167694 0.8698537499794482 0.35050739178155266 0.8785173644970733
2、random.getrandbits(n):
这是返回从0~(2**n - 1)里面的随机一个数
import random num = 0 while num < 10: print(random.getrandbits(3),'\t',end='') # 2**3 - 1 = 7 num += 1 if num % 5 == 0: print()
0 2 7 0 7 4 1 7 5 2
3、random.shuffle(list)
打乱一个列表,将列表里面的元素再重新随机排列,但是对与多维数组来说只能重新排列第一纬度
一维列表:
port random lst = [1 ,2, 3, 4, 5, 6, 7, 8, 9, 0] num = 0 while num < 5: random.shuffle(lst) print(lst) num += 1
[5, 3, 0, 2, 7, 1, 6, 8, 9, 4] [0, 4, 9, 1, 2, 7, 5, 8, 6, 3] [5, 1, 0, 7, 2, 9, 8, 4, 6, 3] [3, 6, 7, 0, 1, 9, 4, 5, 2, 8] [0, 6, 5, 1, 9, 3, 2, 4, 7, 8]
二维列表:
import random lst = [ [4, 5, 6, 7, 8], [0, 2, 1, 3, 9], [0, 5, 0, 5, 4], [1, 2, 3, 4, 5] ] num = 0 while num < 5: random.shuffle(lst) print(lst) num += 1
[[0, 5, 0, 5, 4], [1, 2, 3, 4, 5], [0, 2, 1, 3, 9], [4, 5, 6, 7, 8]] [[1, 2, 3, 4, 5], [0, 2, 1, 3, 9], [4, 5, 6, 7, 8], [0, 5, 0, 5, 4]] [[0, 2, 1, 3, 9], [4, 5, 6, 7, 8], [1, 2, 3, 4, 5], [0, 5, 0, 5, 4]] [[0, 5, 0, 5, 4], [1, 2, 3, 4, 5], [4, 5, 6, 7, 8], [0, 2, 1, 3, 9]] [[0, 2, 1, 3, 9], [4, 5, 6, 7, 8], [1, 2, 3, 4, 5], [0, 5, 0, 5, 4]]