Python sort list with None at the end -
i have homogeneous list of objects none, can contain type of values. example:
>>> l = [1, 3, 2, 5, 4, none, 7] >>> sorted(l) [none, 1, 2, 3, 4, 5, 7] >>> sorted(l, reverse=true) [7, 5, 4, 3, 2, 1, none]
is there way without reinventing wheel list sorted usual python way, none values @ end of list, that:
[1, 2, 3, 4, 5, 7, none]
i feel here can trick "key" parameter
>>> l = [1, 3, 2, 5, 4, none, 7] >>> sorted(l, key=lambda x: (x none, x)) [1, 2, 3, 4, 5, 7, none]
this constructs tuple each element in list, if value none
tuple (true, none)
, if value else (false, x)
(where x
value). since tuples sorted item item, means non-none
elements come first (since false < true
), , sorted value.
Comments
Post a Comment