杰瑞科技汇

Python reverse=True如何实现反转排序?

Of course! The phrase "python reverse true" most commonly refers to the reverse=True argument used in Python's built-in sort() method for lists and the sorted() function.

Python reverse=True如何实现反转排序?-图1
(图片来源网络,侵删)

Let's break down what it does, how it works, and when to use it.

The reverse=True Argument

This argument is used to sort a list or any iterable in descending (high-to-low) order.


list.sort(reverse=True) - Sorting a List In-Place

The sort() method modifies the original list directly. It does not return a new list.

Key Characteristics:

Python reverse=True如何实现反转排序?-图2
(图片来源网络,侵删)
  • In-place: Changes the original list.
  • Returns: None. This is a very common point of confusion for beginners. If you assign the result of my_list.sort() to a variable, that variable will be None.

Example:

# A list of numbers
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print(f"Original list: {numbers}")
# Sort the list in descending order in-place
numbers.sort(reverse=True)
print(f"List after sorting: {numbers}")

Output:

Original list: [3, 1, 4, 1, 5, 9, 2, 6]
List after sorting: [9, 6, 5, 4, 3, 2, 1, 1]

Common Mistake:

my_list = [3, 1, 2]
new_list = my_list.sort(reverse=True) # my_list.sort() returns None
print(f"my_list is: {my_list}")      # my_list is now sorted
print(f"new_list is: {new_list}")    # new_list is None

sorted(iterable, reverse=True) - Creating a New Sorted List

The sorted() function is a built-in that takes any iterable (like a list, tuple, or string) as input and returns a new list containing all items from the iterable in sorted order. The original iterable is not changed.

Key Characteristics:

  • Not In-place: Does not change the original iterable.
  • Returns: A new, sorted list.

Example:

# A tuple of numbers (tuples are immutable, so we can't use .sort() on them)
scores = (88, 95, 72, 100, 61)
print(f"Original tuple: {scores}")
# Create a new list sorted in descending order
sorted_scores = sorted(scores, reverse=True)
print(f"New sorted list: {sorted_scores}")
print(f"Original tuple is unchanged: {scores}")

Output:

Python reverse=True如何实现反转排序?-图3
(图片来源网络,侵删)
Original tuple: (88, 95, 72, 100, 61)
New sorted list: [100, 95, 88, 72, 61]
Original tuple is unchanged: (88, 95, 72, 100, 61)

Sorting with Custom Logic

You can combine reverse=True with the key argument for powerful custom sorting.

The key argument specifies a function to be called on each list element prior to making comparisons.

Example: Sorting a list of dictionaries by a value

Let's sort a list of products by their price, from highest to lowest.

products = [
    {'name': 'Laptop', 'price': 1200},
    {'name': 'Mouse', 'price': 25},
    {'name': 'Keyboard', 'price': 75},
    {'name': 'Monitor', 'price': 300}
]
# Sort the list of dictionaries by the 'price' key in descending order
# The lambda function tells sorted() to use the value of the 'price' key for comparison
sorted_products = sorted(products, key=lambda product: product['price'], reverse=True)
import pprint # For nice printing of dictionaries
pprint.pprint(sorted_products)

Output:

[{'name': 'Laptop', 'price': 1200},
 {'name': 'Monitor', 'price': 300},
 {'name': 'Keyboard', 'price': 75},
 {'name': 'Mouse', 'price': 25}]

How "Reverse" Works Internally

You might wonder what happens under the hood. The sorting algorithm in Python (Timsort) doesn't just iterate backwards. It's more clever than that.

When you use reverse=True, the sorting algorithm compares elements as if you were sorting in ascending order, but then it reverses the result at the very end.

Think of it like this:

  1. The algorithm performs the entire sorting process to find the order [1, 2, 3, 4, 5].
  2. Once that's done, it simply reverses the list to get [5, 4, 3, 2, 1].

This is why reverse=True is very efficient and doesn't slow down the sort significantly.


Summary: list.sort() vs. sorted()

Feature list.sort(reverse=True) sorted(iterable, reverse=True)
What it is A method of the list object. A built-in function.
Action Sorts the list in-place. Returns a new sorted list.
Original Object Is modified. Is not modified.
Return Value None The new sorted list.
Usage my_list.sort(reverse=True) new_list = sorted(my_list, reverse=True)
Applies to Lists only. Any iterable (lists, tuples, strings, etc.).

Quick Reference Table

Goal Method Example
Sort a list, keep original sorted() new_list = sorted(my_list, reverse=True)
Sort a list, discard original list.sort() my_list.sort(reverse=True)
Sort a tuple/string sorted() new_list = sorted(my_tuple, reverse=True)
分享:
扫描分享到社交APP
上一篇
下一篇