Files
Python_CookBook_repo/4.迭代器与生成器/5.反向迭代.py
2025-09-10 16:12:45 +08:00

32 lines
771 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

if __name__ == "__main__":
a = [1, 2, 3, 4]
# python自带的reversed函数搞定了反向迭代其本质时调用了__reversed__方法
for i in reversed(a):
print(i)
for i in a.__reversed__():
print(i)
# 如果想要实现类的反向迭代可以在实现__iter__()方法的同时搞一个__reversed__()方法
class Countdown:
def __init__(self, start):
self.start = start
def __iter__(self):
n = self.start
while n > 1:
yield n
n -= 1
def __reversed__(self):
n = 1
while n <= self.start:
yield n
n += 1
a = Countdown(10)
for i in reversed(a):
print(i)