日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

Python3中迭代器介绍

發布時間:2023/11/27 生活经验 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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中迭代器介绍的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。