我正在尝试编写一个加密程序,生成 8 个不同的随机数并将它们转换为 ASCII。如果可能的话,我想在 python 中使用“随机”函数,但欢迎其他帮助。
到目前为止,我生成数字的代码是将一个值分配给 random.randint()
函数的不同运行 8 次不同的时间,问题是这是草率的。一位 friend 说要使用 random.sample(33, 126, 8)
但我无法让它工作。
非常欢迎任何帮助。
最佳答案
您可以将 xrange
与您的上限和下限一起传递给样本:
from random import sample
print(sample(xrange(33, 126),8))
示例输出:
[49, 107, 83, 44, 34, 84, 111, 69]
或者 python3 的 range
:
print(sample(range(33, 126),8))
示例输出:
[72, 70, 76, 85, 71, 116, 95, 96]
这会给你唯一的数字。
如果你想要 8 个变量:
a, b, c, d, e, f, g, h = sample(range(33, 126), 8)
如果你想要 ascii 你可以 map(chr..)
:
from random import sample
print map(chr,sample(xrange(33, 126), 8))
示例输出:
['Z', 'i', 'v', '$', ')', 'V', 'h', 'q']
关于python - 如何在 python 中生成 8 个不同的随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30154147/