0

I would like to be able to sort a list of strings with each one containing a numerical value and a word.

lst = ["1 Make", "7 William", "35 In", "22 Collins's"]

Desired output:

["1 Make",  "7 William", "22 Collins's", "35 In"]

Using sorted(lst) I get:

["1 Make", "22 Collins's", "35 In", "7 William"]
1
  • 1
    sorted can take a key argument, which is a function applied to the elements of the list to determine the sorted order, i.e. the element x is sorted as if it were key(x). Which leaves you to figure out what function to use. Commented Feb 10, 2018 at 1:44

1 Answer 1

4

This should work:

lst = ["1 Make", "7 William", "22 Collins's", "35 In"]

sorted(lst, key=lambda x: int(x.split(' ')[0]), reverse=True)

# ['35 In', "22 Collins's", '7 William', '1 Make']
Sign up to request clarification or add additional context in comments.

1 Comment

Will work, though probably non-optimal for large sets

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.