目錄
1. 迭代器
2.迭代器對象
3. 可迭代對象
4. range函數(shù)
1. 迭代器
當(dāng)類中定義了__iter__和 __next__兩個方法
- __iter__: 返回對象本身,即self
- __next__: 返回下一個數(shù)據(jù),如果沒有數(shù)據(jù),則拋出StopIteration異常
# 創(chuàng)建迭代器
class IT(object):
def __init__(self):
self.num = 100
def __iter__(self):
return self
def __next__(self):
self.num -= 1
if self.num == -1:
raise StopIteration()
return self.num
2.迭代器對象
通過迭代器類實例化創(chuàng)建的迭代器對象
- 可以通過 obj.__next__() 或 python內(nèi)置函數(shù)next(obj) 來獲取下一個數(shù)據(jù)
- 還支持對迭代器對象進行for循環(huán)【注意:for循環(huán)在內(nèi)部執(zhí)行時,先執(zhí)行__iter__()方法,獲取一個迭代器對象,然后不斷執(zhí)行__next__取值】
# 實例化迭代器對象
it = IT()
# 使用 __next__() 來獲取下一個數(shù)據(jù)
print(it.__next__()) # 9
print(it.__next__()) # 8
# 使用 next(obj) 來獲取下一個數(shù)據(jù)
print(next(it)) # 7
print(next(it)) # 6
# 使用 for 循環(huán)來遍歷數(shù)據(jù)
for item in it:
print(item, end=" ") # 5 4 3 2 1 0
3. 可迭代對象
如果一個類中有__iter__方法并且返回一個迭代器對象,則稱以這個類創(chuàng)建的對象叫可迭代對象。文章來源:http://www.zghlxwxcb.cn/news/detail-426822.html
- 可迭代對象是可以用for來進行循環(huán):與上述對迭代器對象的for循環(huán)步驟相同,先在循環(huán)內(nèi)部先執(zhí)行__iter__方法,獲取迭代器對象,然后再執(zhí)行迭代器對象的__next__函數(shù),逐步取值。
- List,tuple, dict和set都是可迭代對象
class IT2(object):
def __iter__(self):
return IT() # 返回迭代器對象
it2 = IT2() # 生成可迭代對象
for item in IT2():
print(item, end=" ") # 9 8 7 6 5 4 3 2 1 0
4. range函數(shù)
在編程中常見的 range()函數(shù),如 v1=range(100) 返回的是一個可迭代對象v1,因此文章來源地址http://www.zghlxwxcb.cn/news/detail-426822.html
- v2 = v1.__iter__獲取的是迭代器對象,每執(zhí)行一次 next(v2) 就會進行逐步取值
- 或者用for循環(huán)進行遍歷取值
v1 = range(5)
print(isinstance(v1, Iterable)) # True,返回的是可迭代對象
# 1. 使用for循環(huán)遍歷
for v in v1:
print(v, end=" ") # 0 1 2 3 4 0
# 2. 先通過__iter__()獲取迭代器對象,然后使用next獲取到對應(yīng)的值
v1_iterator = v1.__iter__()
print(next(v1_iterator)) # 0
print(next(v1_iterator)) # 1
print(next(v1_iterator)) # 2
print(next(v1_iterator)) # 3
到了這里,關(guān)于Python 基礎(chǔ) - 迭代器 / 迭代器對象 / 可迭代對象 / range函數(shù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!