Sorting by numbers and string

Question:

Say I have a list

['1','2','20', '5', 'undefined', '4']

How do is sort by numbers and put undefined the last? To like this?

['1','2','4', '5', '20', 'undefined']
dirnames.sort(key=int)

This only works without ‘undefined’.

Asked By: test tes

||

Answers:

dirnames.sort(key=lambda s: [1] if s == 'undefined' else [0, int(s)])

or

dirnames.sort(key=lambda s: float('inf') if s == 'undefined' else int(s))
Answered By: Kelly Bundy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.