0

So I have a list that due to some limitations elsewhere has ended up something like the following:

list = ['2. Name','1. Name','3. Name','4. Name','5. Name']

Now I would like to order these by the numbers at the beginning of each string, is that possible? just ordering them throws them into a weird order that is technically right, but not what I'm looking for, e.g:

1, 10, 11, ... , 2, 20, 21 etc

is there a way to get these into a proper numerical order? The numbers appending each string are not necessary, they're only there for me to check the order is correct more easily.

1
  • If possible, create a list of Tuples that contain the number, and the text that you display in your example. Then, sort by the numeric value instead of the string value. Commented Feb 16, 2016 at 16:28

1 Answer 1

1

You can specify the key by which elements need to be sorted:

sorted(list, key=lambda elem: int(elem.split('.')[0]))

A little explanation: split the string using the period char as the delimiter, and use the first token to parse an integer out of it.

As a side-note, avoid naming your variables using predefined keywords. list -> the_list or something of the sort.

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

Comments

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.