杰瑞科技汇

Python reversed()怎么用?[::-1]和它有啥区别?

Of course! Let's dive deep into Python's built-in reversed() function.

Python reversed()怎么用?[::-1]和它有啥区别?-图1
(图片来源网络,侵删)

What is reversed()?

The reversed() function is a built-in Python utility that returns a reverse iterator. An iterator is an object that allows you to traverse through all the values of a collection (like a list or a tuple) one by one. The reversed() function specifically gives you an iterator that yields items from the collection in reverse order.

Key Characteristics

  1. Returns an Iterator, Not a List: This is the most important thing to remember. reversed() does not create a new list, tuple, or string. It creates a list_reverseiterator object. This is very memory-efficient, especially for large sequences, because it doesn't create a copy of the data.
  2. Lazy Evaluation: The iterator only generates values when you ask for them (e.g., when you loop over it). This is part of what makes it memory-efficient.
  3. Consumes the Iterator: Once you iterate over the reversed() object, it's exhausted. You can't use it again to get the items in reverse order. You would have to call reversed() on the original sequence again.

Syntax

reversed(sequence)
  • sequence: This can be any sequence or object that supports the __reversed__() protocol or has a __len__() method and a __getitem__() method with integer indices. Common examples include:
    • list
    • tuple
    • range
    • string (which is a sequence of characters)
    • dict (returns a reverse view of the keys)

How to Use reversed()

Since reversed() returns an iterator, you typically use it in one of three ways:

Converting to a list or tuple

This is the most common way to get a reversed version of a sequence that you can use multiple times.

my_list = [1, 2, 3, 4, 5]
# Create a reversed iterator
reversed_iterator = reversed(my_list)
# Convert the iterator to a list
reversed_list = list(reversed_iterator)
print(reversed_list)
# Output: [5, 4, 3, 2, 1]
# You can also convert it to a tuple
reversed_tuple = tuple(reversed(my_list))
print(reversed_tuple)
# Output: (5, 4, 3, 2, 1)

Using it in a for Loop

You can loop directly over the iterator. This is very memory-efficient as it doesn't create any intermediate list.

Python reversed()怎么用?[::-1]和它有啥区别?-图2
(图片来源网络,侵删)
my_list = ['a', 'b', 'c', 'd']
print("Looping in reverse:")
for item in reversed(my_list):
    print(item, end=' ')
# Output:
# Looping in reverse:
# d c b a

Using it as an Argument

Many functions and methods that accept an iterable (like join(), max(), sum()) can take the reversed() iterator directly.

# Example 1: Using with str.join()
my_string = "hello"
reversed_chars = reversed(my_string)
reversed_string = "".join(reversed_chars)
print(reversed_string)
# Output: olleh
# Example 2: Using with max()
my_list = [10, 99, 42, 7]
# Find the maximum element by checking from the end
last_max = max(reversed(my_list))
print(last_max)
# Output: 99

Common Use Cases

Reversing a String

text = "Python"
reversed_text = "".join(reversed(text))
print(reversed_text)
# Output: nohtyP

Reversing a Tuple

my_tuple = (10, 20, 30, 40)
reversed_tuple = tuple(reversed(my_tuple))
print(reversed_tuple)
# Output: (40, 30, 20, 10)

Reversing a range object

# Create a range object
number_range = range(1, 10)  # Represents numbers 1 through 9
# Reverse it and convert to a list
reversed_range = list(reversed(number_range))
print(reversed_range)
# Output: [9, 8, 7, 6, 5, 4, 3, 2, 1]

Reversing a Dictionary

When used on a dictionary, reversed() iterates over the keys in reverse order of insertion (in Python 3.7+ where dictionaries maintain insertion order).

my_dict = {'a': 1, 'b': 2, 'c': 3}
# Iterate over the reversed keys
for key in reversed(my_dict):
    print(f"Key: {key}, Value: {my_dict[key]}")
# Output:
# Key: c, Value: 3
# Key: b, Value: 2
# Key: a, Value: 1

reversed() vs. Slicing ([::-1])

This is a very common point of confusion. Both can be used to reverse a sequence, but they are different.

Feature reversed(my_list) my_list[::-1]
Return Type Iterator (list_reverseiterator) New List
Memory Usage Very Low. It doesn't create a copy. High. It creates a full copy of the list.
Performance Faster for one-time iteration. Slower if you need to access elements multiple times (since you have to re-iterate). Slower for the initial creation due to copying. Faster for subsequent random access (since it's a list).
Primary Use Case Memory-efficient iteration. When you need a new, reversed list that you can use multiple times.

Example to illustrate the difference:

# A very large list
big_list = list(range(1_000_000))
# 1. Using reversed() - Memory efficient
print("Using reversed():")
for i in reversed(big_list):
    if i == 999_998: # Stop early
        print(f"Found {i}")
        break
# This uses very little memory.
# 2. Using slicing [::-1] - Memory intensive
print("\nUsing slicing [::-1]:")
# This line will consume a lot of memory to create a new list
# with 1 million elements before the loop even starts.
reversed_big_list = big_list[::-1]
for i in reversed_big_list:
    if i == 999_998:
        print(f"Found {i}")
        break

What Can't reversed() Handle?

reversed() requires the object to have a defined order and a known length. It will raise a TypeError if you try to use it on unordered or non-sequence types like sets or generators.

my_set = {3, 1, 2}
try:
    reversed(my_set)
except TypeError as e:
    print(e)
# Output: 'set' object is not reversible
# A generator is also not reversible
my_generator = (x for x in range(5))
try:
    reversed(my_generator)
except TypeError as e:
    print(e)
# Output: 'generator' object is not reversible

Summary

Function What it Does Best For
reversed() Returns a reverse iterator. Memory-efficient iteration. When you just need to loop over items once in reverse.
Slicing [::-1] Returns a new, reversed list. When you need a new list that you can access multiple times, and memory is not a primary concern.
分享:
扫描分享到社交APP
上一篇
下一篇