如何在 python 中生成 8 个不同的随机数?

How do I generate 8 different random numbers in python?

我正在尝试编写一个加密程序,生成 8 个不同的随机数并将它们转换为 ASCII。如果可能的话,我想使用 python 中的 'random' 函数,但欢迎其他帮助。

到目前为止,我生成数字的代码是将一个值分配给 random.randint() 函数的不同 运行 8 次不同的时间,问题是这是草率的。一位朋友说要使用 random.sample(33, 126, 8),但我无法使用它。

非常欢迎任何帮助。

你可以通过xrange你的上限和下限来采样:

from random import sample

print(sample(xrange(33, 126),8))

示例输出:

[49, 107, 83, 44, 34, 84, 111, 69]

range python3:

 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']

从技术上讲,使用 random.sample 不是您想要的 - 值不是独立的,因为在您选择第一个数字(从 93 个选项中)后,您只有 92 个选项用于第二个数字,依此类推。

如果您同意,可以使用 Padraic 的答案。

如果 n(在你的情况下 n = 8)比 N(在你的情况下 N = 126-33 = 93)小得多,这应该没问题,但是 正确答案将是

a, b, c, d, e, f, g, h = [random.randint(93, 126) for _ in xrange(8)]

编辑:更重要的是,如果您决定将 n 增加到 n > N 的状态,您将获得 ValueError

如果您的目标是在 [33..126] 范围内随机选择 8 个 ASCII 字符,您可以直接这样做。首先,该范围内的 ASCII 字符称为 string.printable。您可以使用 random.sample 函数从那里选出 8:

import string
import random

result = random.sample(string.printable, 8)

result 现在是 8 个随机可打印字符的列表。

我推荐使用发电机。仅当您使用 python 2.5 或更高版本时才有效。

from random import randint

def randnums(number, startnum=0, endnum=10):
    for i in range(1, number + 1):
        yield randint(startnum, endnum)

print list(randnums(8, endnum=100))