Python3中迭代器介绍
生活随笔
收集整理的這篇文章主要介紹了
Python3中迭代器介绍
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? ? ? Python中一個可迭代對象(iterable object)是一個實現了__iter__方法的對象,它應該返回一個迭代器對象(iterator object)。迭代器是一個實現__next__方法的對象,它應該返回它的可迭代對象的下一個元素,并在沒有可用元素時觸發StopIteration異常。
? ? ? 當我們使用for循環遍歷任何可迭代對象時,它在內部使用iter()方法獲取迭代器對象,該迭代器對象進一步使用next()方法進行迭代。此方法觸發StopIteration以表示迭代結束。
? ? ? Python中大多數內置容器,如列表、元組、字符串等都是可迭代的。它們是iterable但不是iterator,把它們從iterable變成iterator可以使用iter()函數。
? ? ? 測試代碼如下:
# 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): # 迭代器對象可以使用for語句進行遍歷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
總結
以上是生活随笔為你收集整理的Python3中迭代器介绍的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python3中with用法
- 下一篇: Linux下addr2line命令用法