Python 3.x不支持cmp(list1,list2)函数(Python2.x支持),有无替代方案?
cmp() Function Absolutely! Since Python 3 removed the cmp() function that was available in Python 2, there are several straightforward alternatives depending on your use case:
1. Direct Value Comparison with Operators
For most basic comparisons (checking equality, which value is larger/smaller), you can use Python's built-in comparison operators directly—==, !=, <, >, <=, >=. These work seamlessly with all standard Python types (lists, strings, numbers, etc.):
list1 = [1, 2, 3] list2 = [1, 2, 4] if list1 == list2: print("Lists are equal") elif list1 < list2: print("list1 is smaller than list2") else: print("list1 is larger than list2")
2. Emulate cmp()'s Return Value (-1, 0, 1)
If you specifically need the same integer return style as Python 2's cmp() (where -1 means a < b, 0 means equal, 1 means a > b), you can create a tiny, reusable custom function:
def cmp(a, b): return (a > b) - (a < b) # Example usage print(cmp(5, 3)) # Output: 1 print(cmp(3, 5)) # Output: -1 print(cmp(4, 4)) # Output: 0
This works because in Python, boolean values (True/False) are subclasses of integers—True equals 1 and False equals 0, so the subtraction gives exactly the result we need.
3. Custom Sorting Logic
In Python 2, you could pass a cmp parameter to sort() or sorted() for custom sorting. Python 3 replaced this with the more efficient key parameter, which is the preferred approach for most cases:
# Sort a list of tuples by the second element (Python 3 style) my_tuples = [(1, 3), (2, 1), (3, 2)] my_tuples.sort(key=lambda x: x[1]) # Result: [(2, 1), (3, 2), (1, 3)]
If you have complex sorting logic that can't be easily expressed with a key function, use functools.cmp_to_key() to convert a Python 2-style comparison function into a compatible key function:
from functools import cmp_to_key # Custom comparison: sort strings first by length, then alphabetically def compare_strings(a, b): if len(a) != len(b): return len(a) - len(b) return (a > b) - (a < b) words = ["cat", "apple", "dog", "banana"] sorted_words = sorted(words, key=cmp_to_key(compare_strings)) # Result: ["cat", "dog", "apple", "banana"]
内容的提问来源于stack exchange,提问作者Edward795

