简体   繁体   中英

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?

Why would it matter to execute the sort after the for -loop? The number of comparisons is basically the same. It is actually better to sort it afterward to avoid unnecessary comparisons.

In case you want a two-liner on how to do this with list comprehension:

array = [random.randrange(i, 100) for i in range(10)]
array.sort()
print (sorted([random.randrange(i, 100) for i in range(10)]))

Output:

[8, 26, 48, 62, 68, 77, 78, 83, 94, 96]

If I really understand your meaning, you want to get an sorted array during the loop for each iterative time, that is to say, you want to do something insert into sorted array . bisect can help here.

Following code will ensure array are always sorted in the loop, but not sort each time, it binary search and insert the new element into the array:

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

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