Generate multiple lists with one function

I am doing a small project for a school where I have to compare quicksort with the python built-in sort function. I'm actually already stuck at the beginning, where I need to fill out a few lists with numbers.

def genlist():
    x = []
    while len(x) < 100
        y = randint(1,9999)
        x += [y]
    return x

this is my code. This code works, but it creates only one list. However, my goal is to create multiple lists with different length numbers.

Tried something like this:

def genlist():
    x,y,z = []
    while len(x,y,z) < 100, 1000, 10
        y = randint(1,9999)
        x += [y]
    return x

but does not work, obviously D:

+4
source share
2 answers

I think this is exactly what you need, it is a function that can generate random lists of various lengths:

import random


def main():
    print(generate_list(100))
    print(generate_list(1000))
    print(generate_list(10))


def generate_list(length):
    return [random.randrange(10000) for _ in range(length)]

if __name__ == '__main__':
    main()

Call generate_listwith the length of the list you want to create and use the return result.

+2

- , , :

def genlist():
    x = []
    limit = randint(50, 200)
    while len(x) < limit:
        y = randint(1,9999)
        x.append(y)  # Use the .append() function is more common
    return x

, 50 200.

, Python , , . , .

, , while for. , , , for - .

def genlist():
    x = []
    for _ in range(randint(50, 200)):  # use xrange if you're on Python2
        y = randint(1,9999)
        x.append(y)  # Use the .append() function is more common
    return x

, , - . , []. comps

def genlist():
    x = [randint(1, 9999) for _ in range(randint(50, 200))]
    return x

, , :

def genlist():
    return [randint(1, 9999) for _ in range(randint(50, 200))]

, , - , , , :

def genlist(randmin=1, randmax=9999, minsize=50, maxsize=200):
    return [randint(randmin, randmax) for _ in range(randint(minsize, maxsize)]
+1

Source: https://habr.com/ru/post/1625386/


All Articles