文章目录
Python 3 中的随机数

1 2 3 4 5 6 7 8 9 10 11 |
Python 3.6.8 |Anaconda, Inc.| (default, Dec 29 2018, 19:04:46) Type 'copyright', 'credits' or 'license' for more information IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help. PyDev console: using IPython 6.4.0 Python 3.6.8 |Anaconda, Inc.| (default, Dec 29 2018, 19:04:46) [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin lst = list(range(1,11)) lst Out[3]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] import random |
choice 从特定的序列找到随机值
1 2 3 4 5 6 7 |
random.choice(lst) Out[6]: 9 random.choice(lst) Out[7]: 9 random.choice(lst) Out[8]: 4 |
sample 随机取几个值呢
1 2 3 4 5 6 7 |
random.sample(lst,3) Out[10]: [8, 5, 9] random.sample(lst,3) Out[11]: [1, 7, 5] lst Out[12]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
shuffle 打乱序列
1 2 3 4 5 6 7 8 9 |
random.shuffle(lst) lst Out[15]: [8, 9, 6, 1, 2, 10, 4, 7, 3, 5] lst Out[16]: [8, 9, 6, 1, 2, 10, 4, 7, 3, 5] random.shuffle(lst) lst Out[18]: [8, 2, 7, 3, 4, 9, 1, 6, 10, 5] |
randint 随机产生一个整数
1 2 3 4 5 |
random.randint(1,10) Out[20]: 2 random.randint(1,10) Out[21]: 6 |
random 随机一个浮点数
1 2 3 4 5 6 7 |
random.random() Out[23]: 0.22997267397847143 random.random() Out[24]: 0.8845062988632815 random.random() Out[25]: 0.14172742043242093 |
getrandbits 获取特定比特位的 数值
1 2 3 4 5 |
random.getrandbits(10) Out[27]: 309 random.getrandbits(10) Out[28]: 813 |
