python 反向遍历

2022-05-15  本文已影响0人  孙广宁
4.5 如何反向遍历序列中的元素
>>> a=[1,2,3,5]
>>> for x in reversed(a):
...     print(x)
...
5
3
2
1
>>> f = open('/etc/passwd')
>>> for line in reversed(list(f)):
...     print(line,end='')
...
>>> class C:
...     def __init__(self,start):
...         self.start = start
...     def __iter__(self):
...         n = self.start
...         while n>0:
...             yield n
...         n -= 1
...     def __reversed__(self):
...         n =1
...         while self.start>=n:
...             yield n
...         n +=1
...
>>>
上一篇下一篇

猜你喜欢

热点阅读