4.5 ��迭代¶

问题¶

你想�方�迭代一个�列

解决方案¶

使用内置的 reversed() 函数,比如:

>>> a = [1, 2, 3, 4]
>>> for x in reversed(a):
...     print(x)
...
4
3
2
1

��迭代仅仅当对象的大��预先确定或者对象实现了 __reversed__() 的特殊方法时�能生效。 如果两者都�符�,那你必须先将对象转�为一个列表�行,比如:

# Print a file backwards
f = open('somefile')
for line in reversed(list(f)):
    print(line, end='')

�注�的是如果�迭代对象元素很多的�,将其预先转�为一个列表�消耗大�的内存。

讨论¶

很多程�员并�知��以通过在自定义类上实现 __reversed__() 方法�实现��迭代。比如:

class Countdown:
    def __init__(self, start):
        self.start = start

    # Forward iterator
    def __iter__(self):
        n = self.start
        while n > 0:
            yield n
            n -= 1

    # Reverse iterator
    def __reversed__(self):
        n = 1
        while n <= self.start:
            yield n
            n += 1

for rr in reversed(Countdown(30)):
    print(rr)
for rr in Countdown(30):
    print(rr)

定义一个��迭代器�以使得代��常的高效, 因为它��需�将数�填充到一个列表中然��去��迭代这个列表。