美文网首页
生成1到n范围随机数字的几种思路

生成1到n范围随机数字的几种思路

作者: listems | 来源:发表于2023-04-01 01:08 被阅读0次

1.使用random库

random.choice(range(1, n))
random.randint(1, n)

2.通过时间戳取模

import time
int(time.time() * 100) % n + 1

3. 通过字符串的hash值取模

# 通过输入字符串的不同取到1到n范围内的随机值
int(hash('test')) % n + 1

4 如何获取字母表的随机字母

import string
# 1.通过随机数下标取值
alphabet = string.ascii_lowercase
alphabet[random.randint(0, len(alphabet) - 1)]
# random.choice(string.alphabet)

# 3.通过Ascii码数字随机选取
chr(random.randint(97, 122))

相关文章

网友评论

      本文标题:生成1到n范围随机数字的几种思路

      本文链接:https://www.haomeiwen.com/subject/dfdkddtx.html