Create multiple lists containing random numbers

Asked

Viewed 2,686 times

1

How can I create a code that generates 50 lists with 12 random elements?

I’ve tried to use while to repeat a list generation function, but it did not work very well.

import random

def lista_random():
    lista = []

    while lista != 50:
        for i in range(0,12):
            lista.append(random.randint(1,50))
        lista.sort()
    return lista

lista = lista_random()
print(f'A sua lista é: {lista}')
  • 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?

4 answers

3


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).

2

It’s quite simple, just create the main list (the one that will store the fifty lists) and then create a sub-list to store the 12 random numbers.

Inside of one another for...range you should add the random numbers to the sub-list. See below how it would look:

def lista_random(tamanho = 50):
    lista = []

    for i in range(tamanho):
        sub_lista = []

        for i in range(12):
            sub_lista.append(random.randint(1, 50))
        lista.append(sub_lista)

    return lista

Another much simpler and shorter form is using comprehensilist on thus:

lista_random = lambda tamanho: [[random.randint(1, 50) for i in range(10)] for i in range(tamanho)]

The idea of creating a bond while did not work because you did not check if the list size was different from 50 and yes if the list itself was different from number 50.

What you should have done was use the function len() and to check that the number of items on the list has exceeded 50.

while len(lista) < 50:
    # Código...

Another point where you made a mistake is that you added the numbers to the main list. What you should have done as I showed in the examples above, is to create a sub-list to store the numbers.

0

On this issue it became clear number of lists, which in this case is 50, was also clear the amount of elements, which in this case is 12, however, no mention was made of crease of which you wish to draw lots.

When we wish to carry out some draw, we must make clear the range we will use. To do this we must specify the limits inferior and superior.

Well to resolve this issue we can use the following code:

from random import sample


def lista_random(m, n, i, f):
    lista = list()
    for c in range(1, m + 1):
        lista.append(sorted(sample(range(i, f + 1), n)))
    return lista


num = int(input('Desejas gerar quantas listas? '))
quant = int(input('Quantos números por lista? '))
ini = int(input('Limite inferior do range: '))
fin = int(input('Limite superior do range: '))

for d in lista_random(num, quant, ini, fin):
    print(d)

See here the functioning of the code.

Note that when we execute the code we must enter; the number of lists, the amount of elements of each list, the lower limit of the range and the upper limit of the range and then press enter.

Having entered all these values, they are passed as parameters to the function lista_random(). Inside this function the block for will control the making of all lists. Inside the block for the method sample library random draw n numbers, unrepeated, belonging to the range(i, f + 1), then these values are submitted to the function sorted() and, as a result, ordered increasingly, and finally, such a list is added in lista.

After all these operations return function will display the formed lists.

Observing:

This code is capable of producing and displaying m lists, with n elements from the initial limit i and final limit f of any range.

-3

I came here exactly trying to make a clean code, without conditional, without many loops and functions so that I could generate groups of people and make a code to scramble 23 people from a list and separate them into groups of 6 and the last would be with the remaining 5. The option to use Choices or sample was great, but it’s noisy in the result: even using samples, it doesn’t make you repeat any numbers inside the sublist, but there is "inter-list" repetition and not all members are contemplated because we don’t make an option. pop.

With that I thought it best to do what I thought at first:

  1. generate a list of 23 numbers;
  2. generate 4 empty lists;
  3. use shuffle to shuffle the people list;
  4. Try to use a six-in-six slice collection loop and an if conditional to, when there is no 6, collect what there is.

Tks

  • 1

    Pietro, this area is unique for answers to the question. If you have a new question, create a new one using the "ask a question"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.