Generar enteros aleatorios entre 0 y 9


¿Cómo puedo generar enteros aleatorios entre 0 y 9 (inclusive) en Python?

I. e. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Author: dreftymac, 2010-10-22

16 answers

Intenta:

from random import randint
print(randint(0, 9))

Más información: https://docs.python.org/3/library/random.html#random.randint

 1509
Author: kovshenin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-11 21:38:58
import random
print(random.randint(0,9))

random.randint(a, b)

Devuelve un entero aleatorio N tal que a

Docs: https://docs.python.org/3.1/library/random.html#random.randint

 291
Author: JMSamudio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-30 14:51:01

Prueba esto:

from random import randrange, uniform

# randrange gives you an integral value
irand = randrange(0, 10)

# uniform gives you a floating-point value
frand = uniform(0, 10)
 92
Author: Andrew Hare,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-22 12:55:18
from random import randint

x = [randint(0, 9) for p in range(0, 10)]

Esto genera 10 enteros pseudoaleatorios en el rango de 0 a 9 inclusive.

 53
Author: user14372,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-17 08:05:17

El secrets el módulo es nuevo en Python 3.6. Esto es mejor que el random módulo para usos criptográficos o de seguridad.

Para imprimir aleatoriamente un entero en el rango inclusivo 0-9:

from secrets import randbelow
print(randbelow(10))

Para más detalles, véase PEP 506.

 34
Author: Chris_Rands,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-06 10:40:07

Prueba esto a través de random.shuffle

>>> import random
>>> nums = [x for x in range(10)]
>>> random.shuffle(nums)
>>> nums
[6, 3, 5, 4, 0, 1, 2, 9, 8, 7]
 19
Author: zangw,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-10 17:57:41

Elija el tamaño de la matriz (en este ejemplo, he elegido el tamaño para ser 20). Y luego, use lo siguiente:

import numpy as np   
np.random.randint(10, size=(1, 20))

Puede esperar ver una salida de la siguiente forma ( se devolverán diferentes enteros aleatorios cada vez que lo ejecute; por lo tanto, puede esperar que los enteros en la matriz de salida difieran del ejemplo dado a continuación).

array([[1, 6, 1, 2, 8, 6, 3, 3, 2, 5, 6, 5, 0, 9, 5, 6, 4, 5, 9, 3]])
 13
Author: SiddTheKid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-02 06:35:10

En caso de números continuosrandint o randrange son probablemente las mejores opciones, pero si usted tiene varios valores distintos en una secuencia (es decir, un list) también podría utilizar choice:

>>> import random
>>> values = list(range(10))
>>> random.choice(values)
5

choice también funciona para un elemento de una muestra no continua:

>>> values = [1, 2, 3, 5, 7, 10]
>>> random.choice(values)
7

Si lo necesitas "criptográficamente fuerte" también hay un secrets.choice en python 3.6 y versiones posteriores:

>>> import secrets
>>> values = list(range(10))
>>> secrets.choice(values)
2
 11
Author: MSeifert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-24 10:33:54

Si quieres usar numpy entonces usa lo siguiente:

import numpy as np
print(np.random.randint(0,10))
 8
Author: sushmit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-03 01:39:14

La pregunta original implica generar múltiples enteros aleatorios.

¿Cómo puedo generar enteros entre 0 y 9 (inclusive) en Python?

Sin embargo, muchas respuestas solo muestran cómo obtener un número aleatorio, por ejemplo, random.randint y random.choice.

Múltiples enteros aleatorios

Para mayor claridad, aún puede generar múltiples números aleatorios utilizando esas técnicas simplemente iterando N tiempos:

import random


N = 5

[random.randint(0, 9) for _ in range(N)]
# [9, 7, 0, 7, 3]

[random.choice(range(10)) for _ in range(N)]
# [8, 3, 6, 8, 7]

Muestra de Enteros Aleatorios

Algunos posts demuestran cómo generar nativamente múltiples enteros aleatorios.1 Aquí hay algunas opciones que abordan la pregunta implícita:

random.sample devuelve k selecciones exclusivas de una población (sin reemplazo):2

random.sample(range(10), k=N)
# [4, 5, 1, 2, 3]

En Python 3.6, random.choices devuelve k selecciones de una población (con reemplazo):

random.choices(range(10), k=N)
# [3, 2, 0, 8, 2]

Véase también este post relacionado usando numpy.random.choice.

1A saber, @John Lawrence Aspden, @S T Mohammed, @ SiddTheKid, @user14372, @zangw, et al.

2@prashanth menciona este módulo mostrando un entero.

 6
Author: pylang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-16 04:37:21
>>> import random
>>> random.randrange(10)
3
>>> random.randrange(10)
1

Para obtener una lista de diez muestras:

>>> [random.randrange(10) for x in range(10)]
[9, 0, 4, 0, 5, 7, 4, 3, 6, 8]
 5
Author: John Lawrence Aspden,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-10 15:48:24

random.sample es otro que se puede utilizar

import random
n = 1 # specify the no. of numbers
num = random.sample(range(10),  n)
num[0] # is the required number
 4
Author: prashanth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-14 16:46:54

La mejor manera es usar la función aleatoria de importación

import random
print(random.sample(range(10), 10))

O sin importar ninguna biblioteca:

n={} 
for i in range(10):
    n[i]=i

for p in range(10):
    print(n.popitem()[1])

Aquí el popitems elimina y devuelve un valor arbitrario del diccionario n.

 3
Author: S T Mohammed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-03 01:41:12

Generando enteros aleatorios entre 0 y 9.

import numpy
X = numpy.random.randint(0, 10, size=10)
print(X)

Salida:

[4 8 0 4 9 6 9 9 0 7]
 2
Author: Ashok Kumar Jayaraman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-06 14:11:44

Usé variable para controlar el rango

from random import randint 
numberStartRange = 1
numberEndRange = 9
randomNumber = randint(numberStartRange, numberEndRange)
print(randomNumber)

Utilicé la función print para ver los resultados. Usted puede comentar está fuera si usted no necesita esto.

 0
Author: Amir Md Amiruzzaman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-24 21:12:33

Tuve mejor suerte con esto para Python 3.6

str_Key = ""                                                                                                
str_RandomKey = ""                                                                                          
for int_I in range(128):                                                                                    
      str_Key = random.choice('0123456789')
      str_RandomKey = str_RandomKey + str_Key 

Simplemente agregue caracteres como 'ABCD' y 'abcd ' o'^!~ = - >

 -2
Author: M T Head,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-20 23:43:43