简体   繁体   中英

make a nested list using a for loop and random numbers

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM