mardi 12 janvier 2021

Python: Is there a way to save random numbers in the list as sorted?

I have a code that stores 9 random numbers in the list.

now, I want to sort the values in the list object.

I found two method. but these methods have some problems.

This is my code 1:

import random

array = []
for i in range(1, 10):
    array.append(random.randrange(i, 100))

array.sort()
print(array)

output:

[14, 23, 31, 33, 50, 65, 86, 96, 99]

This code works well, but must be executed after the 'for loop'. I want to execute sort in the 'for loop'.

This is my code 2:

import random

array = []
for i in range(1, 10):
    array.append(random.randrange(i, 100))
    array.sort()

print(array)

output:

[8, 22, 23, 26, 39, 48, 51, 53, 71]

This code works well, but you will run the sort nine times.

Is there any good way?




Aucun commentaire:

Enregistrer un commentaire