In Python 2, there is a comparison function.
A comparison function is any callable that accept two arguments, compares them, and returns a negative number for less-than, zero for equality, or a positive number for greater-than.
In Python 3, the comparison function is replaced with a key function.
A key function is a callable that accepts one argument and returns another value to be used as the sort key.
Now, I've a list of tuple[int, int, str]
that I want to sort, and the string can be S
or E
. There are some tie breaker rules that use values from two tuples.
Given a tuple x: int, y: int, z: str, the rules are as follows:
- If x are equal, and both z = S, larger y comes first.
- If x are equal, and both z = E, smaller y comes first.
- If x are equal, and one z = E another z = S, S record comes first.
A Python 2 style implementation is as follows:
def _cmp(coord1: tuple[int, int, str], coord2: tuple[int, int, str]) -> int:
x1, y1, type1 = coord1
x2, y2, type2 = coord2
if x1 != x2:
return x1 - x2
if type1 == type2:
return y2 - y1 if type1 == "S" else y1 - y2
return -1 if type1 == "S" else 1
Expected output:
[(0, 3, "S"), (0, 2, "S"), (1, 2, "E"), (2, 3, "E")],
[(3, 3, "S"), (4, 2, "S"), (5, 2, "E"), (5, 3, "E")],
[(6, 2, "S"), (7, 3, "S"), (7, 2, "E"), (8, 3, "E")]
I'm aware that a comparison function can be converted to a key function using functools.cmp_to_key; however, I'm wondering if there's a way to implement it directly as a key function since the docs say:
This function is primarily used as a transition tool for programs being converted from Python 2 which supported the use of comparison functions.