sort order for strings of digits

Ian Kelly ian.g.kelly at gmail.com
Wed Oct 31 11:44:10 EDT 2012


On Wed, Oct 31, 2012 at 9:17 AM, djc <djc at kangoo.invalid> wrote:
> The best I can think of is to split the input sequence into two lists, sort
> each and then join them.

In the example you have given they already seem to be split, so you
could just do:

sorted(n, key=int) + sorted(s)

If that's not really the case, then you could construct (str, int)
tuples as sort keys:

sorted(n+s, key=lambda x: ('', int(x)) if x.isdigit() else (x, -1))

Note that the empty string sorts before all numbers here, which may or
may not be desirable.



More information about the Python-list mailing list