How to sort a list in ascending order of its most significant digits? I tried it with radix sort, but it is not working.
def sorrt(l, num, const, place):
ne = []
for i in range(10):
ne.append([])
for i in l:
digit = (i // const) % 10
ne[digit].append(i)
new_list = [element for innerList in ne for element in innerList]
return new_list
def sortmsd(l):
num = max(l)
place = 1
const = 10 ** len(str(num))
const = const // 10
while (num // place > 0):
l = sorrt(l, num, const, place)
const = const // 10
place *= 10
Output should be:
list = [237, 146, 259, 348, 152, 163, 235, 48, 36, 62, 147] # and the sorted list should be
list = [146, 147, 152, 163, 235, 237, 259, 348, 36, 48, 62]
CodePudding user response:
Try:
lst = [237, 146, 259, 348, 152, 163, 235, 48, 36, 62, 147]
print(sorted(lst, key=str))
Prints:
[146, 147, 152, 163, 235, 237, 259, 348, 36, 48, 62]
EDIT:
I used key=str
because I want to compare the items lexicographically (not numerically). E.g. I want "36" > "348" be True
(which is in this case because the two values are strings)