Python3中迭代器介绍
生活随笔
收集整理的這篇文章主要介紹了
Python3中迭代器介绍
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
? ? ? Python中一個(gè)可迭代對(duì)象(iterable object)是一個(gè)實(shí)現(xiàn)了__iter__方法的對(duì)象,它應(yīng)該返回一個(gè)迭代器對(duì)象(iterator object)。迭代器是一個(gè)實(shí)現(xiàn)__next__方法的對(duì)象,它應(yīng)該返回它的可迭代對(duì)象的下一個(gè)元素,并在沒有可用元素時(shí)觸發(fā)StopIteration異常。
? ? ? 當(dāng)我們使用for循環(huán)遍歷任何可迭代對(duì)象時(shí),它在內(nèi)部使用iter()方法獲取迭代器對(duì)象,該迭代器對(duì)象進(jìn)一步使用next()方法進(jìn)行迭代。此方法觸發(fā)StopIteration以表示迭代結(jié)束。
? ? ? Python中大多數(shù)內(nèi)置容器,如列表、元組、字符串等都是可迭代的。它們是iterable但不是iterator,把它們從iterable變成iterator可以使用iter()函數(shù)。
? ? ? 測試代碼如下:
# reference: https://www.programiz.com/python-programming/iterator
my_list = [1, 3, 5] # define a list
if 0:my_iter = iter(my_list) # get an iterator using iter()print(next(my_iter)) # iterate through it using next()print(my_iter.__next__()) # next(obj) is name as obj.__next__()print(my_iter.__next__()) # 5#print(my_iter.__next__()) # this will raise error(StopIteration), no items left
else: # use the for loopfor element in iter(my_list): # 迭代器對(duì)象可以使用for語句進(jìn)行遍歷print(element, end=" ")'''
for element in iterable:# do something with elementIs actually implemented as:
# create an iterator object from that iterable
iter_obj = iter(iterable)
while True: # infinite looptry:# get the next itemelement = next(iter_obj)# do something with elementexcept StopIteration:# if StopIteration is raised, break from loopbreak
'''# reference: https://www.geeksforgeeks.org/iterators-in-python/
class Test:def __init__(self, limit):self.limit = limit# Creates iterator object, Called when iteration is initializeddef __iter__(self):self.x = 10return self# To move to next element. In Python 3, we should replace next with __next__def __next__(self):# Store current value ofxx = self.x# Stop iteration if limit is reachedif x > self.limit:raise StopIteration# Else increment and return old valueself.x = x + 1return x# Prints numbers from 10 to 15
print("\n")
for i in Test(15):print(i, end=" ")print("\n")
value = iter(Test(11))
print(next(value))
print(next(value))
#print(next(value)) # raise StopIterationprint("test finish")
? ? ? GitHub:https://github.com/fengbingchun/Python_Test
總結(jié)
以上是生活随笔為你收集整理的Python3中迭代器介绍的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python3中with用法
- 下一篇: Linux下addr2line命令用法