How to sort a list of sub-lists by the contents of sub-lists, where sub-lists contain strings and booleans?

These handle any lengths, not just length 3. And bools in any places, not just the last column. For keying, they turn each element of each sublist into a tuple.


Solution 1:

sorted(lst1, key=lambda s: [(e is False, e is True, e) for e in s])

Turns strings into (False, False, thestring) so they come first.
Turns True into (False, True, True) so it comes next.
Turns False into (True, False, False) so it comes last.

Though I think of it the reverse way, as in "First deprioritize False, then deprioritize True". The general form is key=lambda x: (shall_come_last(x), x).


Solution 2:

sorted(lst1, key=lambda s: [((e is True) + 2 * (e is False), e) for e in s])

Turns strings into (0, thestring) so they come first.
Turns True into (1, True) so it comes next.
Turns False into (2, False) so it comes last.


Solution 3:

sorted(lst1, key=lambda s: [(0, e) if isinstance(e, str) else (2 - e,) for e in s])

Turns strings into (0, thestring) so they come first.
Turns True into (1,) so it comes next.
Turns False into (2,) so it comes last.