0

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
  • 2
    (Dupe of) How to sort with lambda in Python + some string parsing Commented Aug 31, 2020 at 13:37
  • It does, thank you so much! Commented Aug 31, 2020 at 13:39

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@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.
0
scores = ["bob.21","jeff.46","michael.75","david.12"]

sorted_scores = sorted(scores,key=lambda s: int(s.split('.')[1]))
print(sorted_scores)

output

['david.12', 'bob.21', 'jeff.46', 'michael.75']

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.