Reputation:
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?
Upvotes: 1
Views: 607
Reputation: 346
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))
Upvotes: 1
Reputation: 6090
print (sorted([random.randrange(i, 100) for i in range(10)]))
Output:
[8, 26, 48, 62, 68, 77, 78, 83, 94, 96]
Upvotes: 1
Reputation: 1222
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()
Upvotes: 3