Eduard Eduard - 1 year ago 125
Python Question

How do I generate a random list in Python with duplicates numbers

So I just started programming in Python a few days ago. And now, im trying to make a program that generates a random list, and then, choose the duplicates elements. The problem is, I dont have duplicate numbers in my list.

This is my code:

import random

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

generar_listas(int(input("\nNumero maximo: ")), int(input("Longitud: ")))

And for example, I choose 20 and 20 for random.sample, it generates me a list from 0 to 20 but in random position. I want a list with random numbers and duplicated.

Answer Source

What you want is fairly simple. You want to generate a random list of numbers that contain some duplicates. The way to do that is easy if you use something like numpy.

  • Generate a list (range) of 0 to 10.
  • Sample randomly (with replacement) from that list.

Like this:

import numpy as np
print np.random.choice(10, 10, replace=True)


[5 4 8 7 0 8 7 3 0 0]

If you want the list to be ordered just use the builtin function "sorted(list)"

sorted([5 4 8 7 0 8 7 3 0 0])
[0 0 0 3 4 5 7 7 8 8]

If you don't want to use numpy you can use the following:

print [random.choice(range(10)) for i in range(10)]
[7, 3, 7, 4, 8, 0, 4, 0, 3, 7]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download