杰瑞科技汇

Python for reversed,如何反向遍历序列?

Of course! In Python, "reversed" most commonly refers to the built-in reversed() function, but it can also mean using slicing to reverse a sequence.

Python for reversed,如何反向遍历序列?-图1
(图片来源网络,侵删)

Here’s a complete guide covering both, with clear examples and explanations.


The reversed() Function

The reversed() function is a built-in Python tool that returns a reverse iterator. This is an efficient way to loop over a sequence (like a list, tuple, or string) in reverse order without modifying the original sequence.

Key Characteristics:

  • Returns an Iterator: It doesn't create a new list or copy the data immediately. Instead, it gives you an object that generates items one by one when you loop over it. This is very memory-efficient, especially for large lists.
  • Does Not Modify Original: The original sequence remains unchanged.
  • Works on Sequences and More: It works on any sequence (list, tuple, string, range) and other objects that implement the __reversed__() method (like dictionaries, which reverse their keys).

Syntax:

reversed(sequence)

Examples:

a) Reversing a List

This is the most common use case. Notice the original list is not changed.

Python for reversed,如何反向遍历序列?-图2
(图片来源网络,侵删)
my_list = [1, 2, 3, 4, 5]
# Get the reverse iterator
reversed_iterator = reversed(my_list)
print(f"Original list: {my_list}")
print(f"Reversed iterator object: {reversed_iterator}")
# You can loop over the iterator
print("Looping over the reversed iterator:")
for item in reversed_iterator:
    print(item, end=" ") # Output: 5 4 3 2 1
print("\n")
# To get a new list, you must convert the iterator
new_reversed_list = list(reversed(my_list))
print(f"New reversed list: {new_reversed_list}")
print(f"Original list is still unchanged: {my_list}")

b) Reversing a String

reversed() works on strings too, returning an iterator of characters.

my_string = "hello"
reversed_chars = reversed(my_string)
# Join the characters back into a string
reversed_string = "".join(reversed_chars)
print(f"Original string: '{my_string}'")
print(f"Reversed string: '{reversed_string}'")

c) Reversing a Tuple

Just like lists, you can reverse a tuple.

Python for reversed,如何反向遍历序列?-图3
(图片来源网络,侵删)
my_tuple = ('a', 'b', 'c', 'd')
reversed_tuple = tuple(reversed(my_tuple))
print(f"Original tuple: {my_tuple}")
print(f"Reversed tuple: {reversed_tuple}")

d) Reversing a Dictionary

When you use reversed() on a dictionary, it iterates over the keys in reverse order.

my_dict = {'name': 'Alice', 'age': 30, 'city': 'Paris'}
# Iterate over the keys in reverse order
print("Reversed keys:")
for key in reversed(my_dict):
    print(key, end=" ") # Output: city age name
print("\n")
# To get a reversed dictionary, you need to create a new one
# Note: In Python 3.7+, dictionaries maintain insertion order.
reversed_dict = {key: my_dict[key] for key in reversed(my_dict)}
print(f"Reversed dictionary: {reversed_dict}")

Slicing for Reversal ([::-1])

Another very popular and "Pythonic" way to reverse a sequence is by using slicing. This method is often more concise but is important to understand because it does create a new copy of the data.

Syntax:

sequence[::-1]
  • The first means "start from the beginning".
  • The second means "go to the end".
  • The -1 is the step, which means "go backward by one".

Examples:

a) Reversing a List

my_list = [1, 2, 3, 4, 5]
# Create a new, reversed list using slicing
new_reversed_list = my_list[::-1]
print(f"Original list: {my_list}")
print(f"New reversed list (from slicing): {new_reversed_list}")

b) Reversing a String

This is extremely common for strings.

my_string = "Python"
reversed_string = my_string[::-1]
print(f"Original string: '{my_string}'")
print(f"Reversed string (from slicing): '{reversed_string}'")

c) Reversing a Tuple

my_tuple = ('a', 'b', 'c', 'd')
reversed_tuple = my_tuple[::-1]
print(f"Original tuple: {my_tuple}")
print(f"Reversed tuple (from slicing): {reversed_tuple}")

reversed() vs. Slicing: Which One to Use?

This is a key decision point. Here’s a comparison to help you choose.

Feature reversed() Slicing ([::-1])
Return Type Iterator (memory-efficient) New Sequence (a copy)
Memory Usage Very low. Ideal for huge lists. High. Creates a full copy of the data.
Original Object Unmodified. Unmodified.
Speed Slightly faster for just iterating. Can be faster if you immediately need a new list.
Use Case When you only need to loop over items in reverse. When you need a new, reversed copy of the sequence.
Readability Explicit intent: reversed(my_list). Very concise and idiomatic.
Works On Sequences, Dictionaries, etc. Sequences only (lists, tuples, strings).

Summary & Recommendation

  • Use reversed() when:

    • You are working with a very large list and want to save memory.
    • You only need to iterate through the items in reverse order once.
    • You want to be explicit about your intent to iterate.
  • Use Slicing ([::-1]) when:

    • You need a brand new, reversed list, string, or tuple.
    • You prefer the concise, idiomatic syntax.
    • You are sure the memory cost of creating a copy is acceptable.

For most everyday tasks, especially with small to medium-sized data, slicing ([::-1]) is often preferred for its simplicity and readability. However, for performance-critical applications or very large datasets, reversed() is the superior choice due to its memory efficiency.

分享:
扫描分享到社交APP
上一篇
下一篇