反向迭代和迭代切片
-
反向迭代
問題:你想反方向迭代一個序列
通常做法:使用內(nèi)置的 reversed() 函數(shù)
>>> a=[1,2,3,4,5]
>>> for x in reversed(a):
print(x)
5
4
3
2
1
>>>
??反向迭代僅僅當(dāng)對象的大小可預(yù)先確定或者對象實現(xiàn)了__reversed__ ()的特殊方法時才能生效。如果兩者都不符合,那你必須先將對象轉(zhuǎn)換為一個列表才行。如果可迭代對象有很多元素時,需要消耗很大內(nèi)存占用。因此可自定義一個反向迭代器。
#示例:實現(xiàn)實現(xiàn)了` __reversed__ () `的特殊方法
>>> class CountDown:
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 n<=self.start:
yield n
n+=1
>>> for rr in CountDown(4):
print(rr)
4
3
2
1
>>>
-
迭代器切片
問題:在迭代器或者生成器上做切片操作,由于事先的長度位置及不能做索引操作,標(biāo)準(zhǔn)切片操作并不可用。
方法:函數(shù) itertools.islice() 正好適用于在迭代器和生成器上做切片操作。
原理:它通過遍歷并丟棄直到切片開始索引位置的所有元素。然后才開始一個個的返回元素,并直到切片結(jié)束索引位置。其中,值得注意的是:islice() 會消耗掉傳入的迭代器中的數(shù)據(jù)。必須考慮到
迭代器是不可逆的這個事實。
#操作上述CountDown
>>> cd=CountDown(10)
>>> cd[2:8]
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
cd[2:8]
TypeError: 'CountDown' object is not subscriptable
>>> import itertools
>>> for x in itertools.islice(cd,2,8):
print(x)
8
7
6
5
4
3
>>>
None參數(shù)為默認(rèn)值,它的使用類似[2:] 和 [:2]原理是一樣的
>>>#獲取從第 8個到最后的所有元素
>>> for x in itertools.islice(cd,2,None):
print(x)
8
7
6
5
4
3
2
1
>>> 獲取前2個元素
>>> for x in itertools.islice(cd,None,2):
print(x)
10
9
>>>