Souvik Ray
Souvik Ray

Reputation: 3018

Sort a list on the basis of first digit of the elements

Here is what I want

lis = [55,57,7,48,73,5]

After sorting on the basis of first digit in descending order

lis = [73,7,57,55,5,48]

This is what I tried but it only returns complete numbers in decreasing order

lis.sort(reverse=True)
lis = [73,57,55,48,7,5]

Upvotes: 1

Views: 5868

Answers (2)

Victor deMatos
Victor deMatos

Reputation: 963

THAT SORTING HAPPENS WITH STRINGS

If you were to sort an int list e.g:

a = [1, 2, 3, 4, 5, 10, 11, 12, 13, 20, 22, 30]
print(sorted(a))

>>>
[1, 2, 3, 4, 5, 10, 11, 12, 13, 20, 22, 30]

Now if you were to sort that same list, but each element is a string object:

a = ['1', '2', '3', '4', '5', '10', '11', '12', '13', '20', '22', '30']
print(sorted(a))

>>>
['1', '10', '11', '12', '13', '2', '20', '22', '3', '30', '4', '5']

Upvotes: 1

victor
victor

Reputation: 1644

I'll adapt the answer in the question I linked, since that solution involves reading from a file (though the answer is extremely similar). The sort() function accepts a parameter called key that indicates a function to use when sorting the list.

lis.sort(key=lambda x: int(str(x)[0]))

In the above function, int(str(x)[0]) converts each element into a string, takes the first character (which would be the first digit), and converts that back into an integer. Python then sorts the numbers based on that first digit.

Upvotes: 4

Related Questions