# 4.5 反向迭代¶

## 解决方案¶

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

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

## 讨论¶

```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)
```
{"ft_lang_label":"__label__zh","ft_lang_prob":0.6820365,"math_prob":0.85342366,"size":768,"snap":"2021-04-2021-17","text_gpt3_token_len":396,"char_repetition_ratio":0.12565444,"word_repetition_ratio":0.0,"special_character_ratio":0.3203125,"punctuation_ratio":0.18248175,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9801265,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-04-20T04:12:28Z\",\"WARC-Record-ID\":\"<urn:uuid:df6a5462-dffc-424e-b464-a5cf4cb04b03>\",\"Content-Length\":\"19887\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:1e474480-22d6-47e1-8274-744486bf6067>\",\"WARC-Concurrent-To\":\"<urn:uuid:dee5edcb-3a3e-4624-b44c-9562c9700b0b>\",\"WARC-IP-Address\":\"104.17.32.82\",\"WARC-Target-URI\":\"https://python3-cookbook-personal.readthedocs.io/zh_CN/latest/c04/p05_iterating_in_reverse.html\",\"WARC-Payload-Digest\":\"sha1:M7AZGMGFWPU6YX6N4AKAJD2SK2JZOLMO\",\"WARC-Block-Digest\":\"sha1:URR2S3JDLVBN6XS4XHQORFVPLF7HZPEX\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-17/CC-MAIN-2021-17_segments_1618039375537.73_warc_CC-MAIN-20210420025739-20210420055739-00251.warc.gz\"}"}