Files
Python_CookBook_repo/3.数字日期和时间/11.随机选择.py
2025-09-10 16:12:45 +08:00

34 lines
1.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import random
from gevent.subprocess import value
if __name__ == '__main__':
# 如果想要进行随机数操作那么random库是我们最好的选择
values = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 使用random.choice进行抽卡
random_num = random.choice(values)
print(random_num)
# 使用random.choices进行多次抽卡(k次),每次抽一张
random_nums = random.choices(values, k=2)
print(random_nums)
# 使用random.sample进行抽卡并剔除,这个函数只抽取一次每次抽k张所以k不能大于数组长度
random_num = random.sample(values, k=3)
print(random_num)
# 如果只是想洗牌那用shuffle就行了
random.shuffle(values) # 注意,这个函数不返回任何东西,它直接在原数组上进行操作
print(values)
# 生成随机数可以使用random.randint, 它接受两个参数生成a和b之间的随机数
print(random.randint(0, 10))
# 如果要0-1之间的float可以用random.random
print(random.random())
# 在配密钥的时候我们有的时候会想要得到N比特位的随机整数这时候可以用random.getrandbits(n)
print(random.getrandbits(12))
# 切记random虽然可以产生随机数但其使用的梅森旋转算法是确定算法只要破解seed就能计算出固定值
# 如果需要在密钥中搞到随机数请使用ssl模块产生随机加密字节