Home > Blockchain >  Sorting by numbers and string
Sorting by numbers and string

Time:01-28

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

CodePudding user response:

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