To generate a list of random numbers, you do not need to make a loop and add the numbers one by one. The module random
already has two functions ready for this: choices
and sample
. For example, to generate a list of 12 random numbers between 1 and 50:
from random import choices, sample
tamanho = 12
valores = range(1, 51)
print(choices(valores, k=tamanho))
print(sample(valores, tamanho))
Obs: choices
is only available from Python 3.6
In your code you used randint(1, 50)
, that generates a random number between 1 and 50. To get the same effect, we have to use range(1, 51)
, since a range
does not include the last number.
Both generate a list with the specified size. The difference is that choices
can put repeated values in the list (same number may appear more than once), while sample
ensures that there will be no repeats. Choose the one that is most appropriate for your case (your current code allows repeats, since each call from randint
is "independent" and there is no guarantee that the generated numbers will be unique in the list).
To generate 50 lists, just create a list of lists and make one for
simple to add the lists:
from random import choices
qtd = 50
tamanho = 12
valores = range(1, 51)
listas = []
for _ in range(qtd):
listas.append(choices(valores, k=tamanho))
print(listas)
Or, using the syntax of comprehensilist on, much more succinct and pythonic:
from random import choices
qtd = 50
tamanho = 12
valores = range(1, 51)
listas = [ choices(valores, k=tamanho) for _ in range(qtd) ]
print(listas)
I saw that you are ordering the lists, so one way to do it is to use sorted
:
listas = [ sorted(choices(valores, k=tamanho)) for _ in range(qtd) ]
Or, if you prefer to continue using sort
:
listas = []
for _ in range(qtd):
lista = choices(valores, k=tamanho)
lista.sort()
listas.append(lista)
The difference is that sorted
returns another list (ie, choices
returns a list, which is passed to sorted
, which returns another list), while list.sort()
sorts the list in place (modifies the elements of the list itself, without creating another).
Let me get this straight. There are 50 lists of lists, each of which lists within the list must have 12 random numbers between 1 and 50 in ascending order. That’s it?
– Victor Stafusa