杰瑞科技汇

python cmp import

Of course! Let's break down the history and usage of cmp in Python.

python cmp import-图1
(图片来源网络,侵删)

The Short Answer

In Python 2, you could use the built-in function cmp().

In Python 3, the cmp() function has been removed. You should use the <, >, or operators for comparisons, or the functools.cmp_to_key() function if you need to convert a comparison function to a key function for sorting.


Detailed Explanation

The cmp() Function in Python 2

In Python 2, cmp(a, b) was a built-in function that compared two objects, a and b. It returned:

  • A negative integer if a < b
  • Zero if a == b
  • A positive integer if a > b

Example (Python 2 Code)

# This code ONLY works in Python 2
a = 10
b = 20
print cmp(a, b)   # Output: -1  (because 10 < 20)
print cmp(b, a)   # Output: 1   (because 20 > 10)
print cmp(a, a)   # Output: 0   (because 10 == 10)
# It also works with strings
print cmp("apple", "banana") # Output: -1 (because 'apple' comes before 'banana')

Why Was cmp() Removed in Python 3?

The primary reason for removing cmp() was to encourage the use of "rich comparison" methods (__lt__, __gt__, __eq__, etc.) and to simplify the language.

python cmp import-图2
(图片来源网络,侵删)
  • Rich Comparisons are More Explicit: The <, >, operators are more readable and directly express the intent of the comparison. x < y is clearer than cmp(x, y) < 0.
  • Performance: Comparisons using operators can be faster as they can be short-circuited. For example, in a < b < c, if a < b is false, Python doesn't even need to check b < c. A function call like cmp() cannot be short-circuited.
  • Simplicity: It reduces redundancy. The logic of cmp() can be easily replicated with the standard operators.

How to Compare in Python 3

For simple comparisons, just use the standard operators.

Example (Python 3 Code)

a = 10
b = 20
# Instead of cmp(a, b) < 0, you write:
if a < b:
    print(f"{a} is less than {b}") # Output: 10 is less than 20
# Instead of cmp(a, b) == 0, you write:
if a == b:
    print("They are equal")
# You can chain comparisons for clarity
if 0 < a < 100:
    print(f"{a} is between 0 and 100") # Output: 10 is between 0 and 100

The Special Case: Sorting with cmp

The most common use case for cmp() was for custom sorting. In Python 2, the list.sort() method and the sorted() function had a cmp argument that accepted a comparison function.

# Python 2 sorting example
students = [('John', 'Doe', 25), ('Jane', 'Doe', 22), ('Dave', 'Smith', 30)]
# Sort by age (the third element in the tuple)
def compare_students(student1, student2):
    return cmp(student1[2], student2[2])
students.sort(cmp=compare_students)
print(students)
# Output: [('Jane', 'Doe', 22), ('John', 'Doe', 25), ('Dave', 'Smith', 30)]

The Python 3 Solution: functools.cmp_to_key()

Since Python 3 doesn't have a cmp argument for sorting, you need to convert your old-style cmp function into a key function. This is done using functools.cmp_to_key().

A key function is different: it takes one item and returns a value that Python can use to compare that item (e.g., its numeric value, its first letter, etc.). cmp_to_key cleverly wraps your cmp function so it behaves like a key function.

python cmp import-图3
(图片来源网络,侵删)

Example (Python 3 Sorting)

import functools
students = [('John', 'Doe', 25), ('Jane', 'Doe', 22), ('Dave', 'Smith', 30)]
# 1. Define the comparison function (same as in Python 2)
def compare_students(student1, student2):
    # Returns -1, 0, or 1 based on age comparison
    if student1[2] < student2[2]:
        return -1
    elif student1[2] > student2[2]:
        return 1
    else:
        return 0
# 2. Use functools.cmp_to_key to convert it to a key function
# 3. Use the new key function in the sort() method
students.sort(key=functools.cmp_to_key(compare_students))
print(students)
# Output: [('Jane', 'Doe', 22), ('John', 'Doe', 25), ('Dave', 'Smith', 30)]

Summary Table

Feature Python 2 Python 3
Comparison Function cmp(a, b) is a built-in function. cmp() is not defined.
Simple Comparison if cmp(a, b) < 0: if a < b: (Recommended)
Custom Sorting my_list.sort(cmp=my_cmp_function) my_list.sort(key=functools.cmp_to_key(my_cmp_function))
Pythonic Way cmp() was common. Use <, >, operators. For sorting, prefer a key function that returns a value (e.g., key=lambda x: x[1]).

Modern Python 3 Sorting (The Best Way)

While cmp_to_key is the solution for converting old code, the most "Pythonic" way to sort in Python 3 is to use a lambda function with the key argument. This is often more direct and readable.

students = [('John', 'Doe', 25), ('Jane', 'Doe', 22), ('Dave', 'Smith', 30)]
# Sort by age (the 3rd element, index 2) using a lambda key
students.sort(key=lambda student: student[2])
print(students)
# Output: [('Jane', 'Doe', 22), ('John', 'Doe', 25), ('Dave', 'Smith', 30)]
# Sort by last name (the 2nd element, index 1)
students.sort(key=lambda student: student[1])
print(students)
# Output: [('Dave', 'Smith', 30), ('Jane', 'Doe', 22), ('John', 'Doe', 25)]
分享:
扫描分享到社交APP
上一篇
下一篇