Python number alignment. I have a quick question. Sort by the first digit.

Asked 2 years ago, Updated 2 years ago, 85 views

When numbers from 1 to 100 are mixed together
I know that sort is sorted in ascending order, but

1, 10, 11, ... , 100, 2, 20, ... , 29, ... , 9, 90, ... , 99

How do I sort by the first digit in this way?

python sorting

2022-09-21 11:34

2 Answers

Convert to string and then sort.


2022-09-21 11:34

values = [1, 2, 9, 10, 11, 20, 29, 90, 99, 100]
print(sorted(map(str, values))) # ['1', '10', '100', '11', '2', '20', '29', '9', '90', '99']

The map function applies str to each element of values.

--- Add---
It's better to do it like @digda Haha

print(sorted(values, key=str))

This is much better


2022-09-21 11:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.