test tes
test tes

Reputation: 131

Sorting by numbers and string

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'.

Upvotes: 1

Views: 48

Answers (1)

Kelly Bundy
Kelly Bundy

Reputation: 27609

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))

Upvotes: 2

Related Questions