Python: 反方向迭代一个序列
生活随笔
收集整理的這篇文章主要介紹了
Python: 反方向迭代一个序列
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用內置的reversed()函數
>>> a = [1, 2, 3, 4] >>> for x in reversed(a): ... print(x)out 4 3 2 1反向迭代僅僅當對象的大小可預先確定或者對象實現了 _reversed_()的特殊方法時才能生效。如果兩者都不符合 ,必須將對象轉換成一個列表才行。
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 += 1for rr in reversed(Countdown(30)): print(rr) for rr in Countdown(30): print(rr)?定義一個反向迭代器可以使得代碼非常的高效,因為它不再需要將數據填充到一個列表中然后再去反向迭代這個列表。
?
轉載于:https://www.cnblogs.com/baxianhua/p/9995712.html
總結
以上是生活随笔為你收集整理的Python: 反方向迭代一个序列的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python对landsat8数据进行辐
- 下一篇: [转载]辐射定标、辐射校正、几何校正的区