You're effectively sorting on two keys: the primary key is whether the int is even or odd, and you want odd to compare "smaller". The secondary key is then the integer itself. That can all be expressed by sorting on tuples of (primary key, secondary key), which can be expressed by building those tuples straightforwardly via a function passed to sorting's optional key=
argument:
>>> li = [4, 1, 5, 8, 2, 9, 3, 10, 7, 6]
>>> sorted(li, key=lambda i: (1 - (i & 1), i))
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
Alternative: in any case where you're sorting on N
keys, instead of doing a single sort with N
-tuple keys, you can instead do N
sorts on the individual keys, least-significant key first. This may well not be obvious, and relies on that Python's sorting algorithm is "stable" (preserves the input order of items that compare equal). Concretely, for the case at hand, here's one way to do that:
>>> sorted(sorted(li), key=lambda i: i % 2, reverse=True)
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
For reasons that are uncomfortably involved, it can be faster to do it this way. Despite that you're doing more sorts, it's possible that cheaper comparisons can more than make up for that.