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.
Code
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 71What 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
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.