cmp_to_key Restores Comparator Sorting

cmp_to_key wraps a two-element comparator for sorted when directions conflict, like ascending departments with a descending string field that cannot be negated.

PythonData Integrity

Code

pythonsnippet
18 lines
from functools import cmp_to_key

# 部门升序、同部门按积分降序:数字可以 -x 翻转方向,字符串无法取负,
# 方向相反的两段比较只能写成元素之间的比较函数
def compare(a, b):
    if a["dept"] != b["dept"]:
        return -1 if a["dept"] < b["dept"] else 1
    return b["score"] - a["score"]

rows = [
    {"dept": "platform", "score": 71},
    {"dept": "api", "score": 88},
    {"dept": "api", "score": 92},
    {"dept": "billing", "score": 60},
]

for row in sorted(rows, key=cmp_to_key(compare)):
    print(row["dept"], row["score"])

Output

Captured from a sandboxed run of this snippet in the build pipeline.

api 92
api 88
billing 60
platform 71

What the code does

cmp_to_key Restores Comparator Sorting keeps everything in the function compare.

Repetition is confined to for row in sorted(rows, key=cmp_to_key(compare)) — the rest of the file is straight-line.

Applying it

Entry signature: def compare(a, b)

compare is the public entry point; everything else in the file exists to support it.

Statements that matter

def compare(a, b):
    if a["dept"] != b["dept"]:
        return -1 if a["dept"] < b["dept"] else 1
    return b["score"] - a["score"]

Interactive Tools for This Topic

FAQ

Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. Every import resolves inside the standard library — `functools`. The file defines `compare` at load time.