Create a list of random numbers in python

0

I'm trying to create a list of random numbers in python. I managed to create it but I just want to see the int () type and I see all types of float (), does anyone know what I can do? This is what I did:

import random
def listaAleatorios(n):
      lista = [0]  * n
      for i in range(n):
          lista[i] = random.random()
      return lista

print("Ingrese cuantos numeros aleatorios desea obtener")
n=int(input())

aleatorios=listaAleatorios(n)
print(aleatorios)
    
asked by Estanislao Ortiz 11.12.2017 в 23:13
source

2 answers

1

Use random.randint instead of random.random since the latter returns pseudorandom values between 0.0 and 1.0. But keep in mind that you have to specify the range in which you want these random numbers to be, randint receives two parameters, the first is the lower limit of the range and the second the upper one, both can be chosen.

import random

def listaAleatorios(n):
      lista = [0]  * n
      for i in range(n):
          lista[i] = random.randint(0, 1000)
      return lista

print("Ingrese cuantos numeros aleatorios desea obtener")
n=int(input())

aleatorios=listaAleatorios(n)
print(aleatorios)

Or simply:

import random


print("Ingrese cuantos numeros aleatorios desea obtener")
n=int(input())
aleatorios = [random.randint(0,1000) for _ in range(n)]
print(aleatorios)

In this case you get random numbers between 0 and 1000, if you want another range pass it to randint according to your needs.

    
answered by 11.12.2017 в 23:20
-1

It may also be useful to use random.randrange , which in addition to returning integers, adds a jump in the range.

For example, if you need only even integers:

import random

def listaAleatorios(n):
    lista = []
    for i in range(n):
        lista.insert(i, random.randrange(0, 1000, 2))
    return lista

print("Ingrese cuantos numeros aleatorios desea obtener")
n = int(input())

aleatorios = listaAleatorios(n)
print(aleatorios)
    
answered by 12.12.2017 в 01:49