如何生成一堆没有重复但在一定范围内且Python的随机数列表?

How to generate a bunch of lists of random numbers which have no repeats but in a certain range with Python?

我实际上需要生成一堆 1 到 5 范围内的随机数列表。我知道如何使用 shuffle 模块生成一个 1 到 5 范围内的随机数列表,但是如果我想要一堆这样的东西? 我不知道使用循环,有没有人可以帮忙? 很多人欣赏~

import numpy as np
import random as rd
hh = list(range(1,6))
rd.shuffle(hh)

print(hh)

我只想重复这段代码500次 并得到一个组装输出

import random

f = []
for i in range(5):
    f.append(random.sample(range(5), 5))
print(f)

x = [random.sample(range(5), 5) for i in range(5)]
print(x)


[[3, 0, 1, 4, 2], [4, 2, 0, 3, 1], [4, 0, 1, 3, 2], [3, 0, 1, 2, 4], [4, 3, 2, 0, 1]]

在Python标准库中,有random.sample()直接解决问题:

>>> from random import sample
>>> sample(range(2_400, 8_800, 100), k=10)
[6200, 7000, 3600, 7800, 6900, 5500, 4000, 7700, 5200, 2800]

sample() 函数从范围中选择值而不进行替换。

要允许重复(带替换的选择),请使用 random.choices():

>>> from random import choices
>>> choices(range(2_400, 8_800, 100), k=10)
[2500, 5400, 7600, 2500, 3500, 2600, 5400, 5200, 3700, 7600]

对于 numpy 使用 numpy.random.choice()。它有替换或不替换的选项。

您可以使用numpy

num_range = np.random.default_rng()
num_range.choice(10, size=5, replace=False)

array([7, 8, 4, 3, 0], dtype=int64)