AntlerFox
AntlerFox

Reputation: 180

Order a list of numbered strings in Python

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.

Upvotes: 0

Views: 33

Answers (1)

Cajetan Rodrigues
Cajetan Rodrigues

Reputation: 172

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.

Upvotes: 1

Related Questions