Home > Blockchain >  make a nested list using a for loop and random numbers
make a nested list using a for loop and random numbers

Time:09-05

I am looking to make a nested list. In each list I will have random numbers generated from 1 - 80 and 1000 lists. I have the random number part down, but can not make the nested list. this is what I have.

def lots_of_draws ():
    numbers_to_draw_from = list(range(1, 81))
    random_draws = sorted(random.sample(numbers_to_draw_from, k=20,))
    random_draws_list = []
    time_ = 0
    while time_ > 100:
        random_draws_list.append(random_draws)
        time_ =1
        print(time_)

    print(random_draws_list)
lots_of_draws()

expected [[1,2,3,4,5,6,7,8,9,11,12,13,20,50,45,58,32,78,80,16],[another 20],[anoter 20],and so on for 100, or 1000]

I don't know what I doing wrong, any help would be great. Thanks

CodePudding user response:

The following code will also fix your problem.

from random import randint

def lots_of_draws():
    main_list = []
    for i in range(1000):
       nested_list = []
       for i in range(20):
           nested_list.append(randint(0,80))
       main_list.append(nested_list)
    return main_list

CodePudding user response:

First issue is that your while loop will never run. You probably want while time_ < 100 instead. You'll still not get the expected result after fixing that though, because on each iteration, you're appending the same list to random_draws_list. random_draws is only created once.

Possible fix:

def draw_n(numbers, n):
    return sorted(random.sample(numbers, k=n))


def lots_of_draws():
    numbers_to_draw_from = range(1, 81)
    random_draws_list = []
    for time_ in range(100):
        random_draws_list.append(draw_n(numbers_to_draw_from, 20))
        print(time_)

    print(random_draws_list)
  • Related