如何在 Python 中生成带有重复数字的随机列表

iMa*_*sck 2 python list

所以我几天前才开始用 Python 编程。现在,我正在尝试制作一个生成随机列表的程序,然后选择重复的元素。问题是,我的列表中没有重复的数字。

这是我的代码:

import random

def generar_listas (numeros, rango):
    lista = [random.sample(range(numeros), rango)]
    print("\n", lista, sep="")
    return
def texto_1 ():
    texto = "Debes de establecer unos parámetros para generar dos listas aleatorias"
    print(texto)
    return

texto_1()
generar_listas(int(input("\nNumero maximo: ")), int(input("Longitud: ")))
Run Code Online (Sandbox Code Playgroud)

例如,我为 random.sample 选择了 20 和 20,它为我生成了一个从 0 到 20 但位置随机的列表。我想要一个包含随机数并重复的列表。

Moh*_*ubi 6

你想要的很简单。您想要生成包含一些重复项的随机数字列表。如果您使用类似 numpy.

  • 生成 0 到 10 的列表(范围)。
  • 从该列表中随机抽样(替换)。

像这样:

import numpy as np
print np.random.choice(10, 10, replace=True)
Run Code Online (Sandbox Code Playgroud)

结果:

[5 4 8 7 0 8 7 3 0 0]
Run Code Online (Sandbox Code Playgroud)

如果您希望对列表进行排序,只需使用内置函数“sorted(list)”

sorted([5 4 8 7 0 8 7 3 0 0])
[0 0 0 3 4 5 7 7 8 8]
Run Code Online (Sandbox Code Playgroud)

如果您不想使用 numpy,则可以使用以下命令:

print [random.choice(range(10)) for i in range(10)]
[7, 3, 7, 4, 8, 0, 4, 0, 3, 7]
Run Code Online (Sandbox Code Playgroud)