I have the following list, which was created from a file:
scores=["bob.21","jeff.46","michael.75","david.12"]
How can I sort items of this list based on the integer within each item?
-
2(Dupe of) How to sort with lambda in Python + some string parsinghnefatl– hnefatl2020-08-31 13:37:33 +00:00Commented Aug 31, 2020 at 13:37
-
It does, thank you so much!Awesome Guy– Awesome Guy2020-08-31 13:39:45 +00:00Commented Aug 31, 2020 at 13:39
Add a comment
|
2 Answers
Use a key function that parses out the integer:
scores.sort(key=lambda x: int(x.partition('.')[2]))
That just logically sorts it as if the values were [21, 46, 75, 12] while preserving the original values.
1 Comment
ShadowRanger
@timgeb: Not when they're all two digits long (though it's harmless to convert, and might make the comparisons infinitesimally faster). But it's absolutely necessary if there might be a different number of digits.
20 < 3 is false, but '20' < '3' is true.