Python iter() 函數返回給定對象的迭代器。
iter()
函數創建一個可以一次迭代一個元素的對象。
這些對象在與 for loop 、 while loop 等循環結合使用時很有用。
用法:
iter(object, sentinel)
參數:
iter()
函數有兩個參數:
返回:
iter()
函數返回給定對象的迭代器對象。- 如果用戶定義的對象沒有實現
__iter__()
和__next__()
或__getitem()__
,則會引發TypeError
異常。 - 如果還提供了 sentinel 參數,則
iter()
返回一個迭代器,直到找不到 sentinel 字符。
示例 1:Python iter() 的工作
# list of vowels
vowels = ['a', 'e', 'i', 'o', 'u']
vowels_iter = iter(vowels)
print(next(vowels_iter)) # 'a'
print(next(vowels_iter)) # 'e'
print(next(vowels_iter)) # 'i'
print(next(vowels_iter)) # 'o'
print(next(vowels_iter)) # 'u'
輸出
a e i o u
示例 2:iter() 用於自定義對象
class PrintNumber:
def __init__(self, max):
self.max = max
def __iter__(self):
self.num = 0
return self
def __next__(self):
if(self.num >= self.max):
raise StopIteration
self.num += 1
return self.num
print_num = PrintNumber(3)
print_num_iter = iter(print_num)
print(next(print_num_iter)) # 1
print(next(print_num_iter)) # 2
print(next(print_num_iter)) # 3
# raises StopIteration
print(next(print_num_iter))
輸出
1 2 3 Traceback (most recent call last): File "", line 23, in File " ", line 11, in __next__ StopIteration
示例 3:iter() 帶哨兵參數
class DoubleIt:
def __init__(self):
self.start = 1
def __iter__(self):
return self
def __next__(self):
self.start *= 2
return self.start
__call__ = __next__
my_iter = iter(DoubleIt(), 16)
for x in my_iter:
print(x)
輸出
2 4 8
在這裏,我們實現了一個沒有StopIteration
條件的自定義可迭代對象。
但是,我們可以使用帶有sentinel
參數的iter()
方法來停止迭代。如果從__next__()
返回的值等於sentinel
, StopIteration
將被提升,否則將返回該值。
相關用法
- Python iter()用法及代碼示例
- Python itertools.groupby()用法及代碼示例
- Python itertools.repeat()用法及代碼示例
- Python calendar itermonthdays2()用法及代碼示例
- Python calendar itermonthdays()用法及代碼示例
- Python calendar itermonthdates()用法及代碼示例
- Python calendar iterweekdays()用法及代碼示例
- Python dict items()用法及代碼示例
- Python string isalnum()用法及代碼示例
- Python id()用法及代碼示例
- Python string isidentifier()用法及代碼示例
- Python numpy irr用法及代碼示例
- Python calendar isleap()用法及代碼示例
- Python math isclose()用法及代碼示例
- Python string isupper()用法及代碼示例
- Python scipy integrate.trapz用法及代碼示例
- Python numpy matrix identity()用法及代碼示例
- Python int轉exponential用法及代碼示例
- Python integer轉string用法及代碼示例
- Python issubclass()用法及代碼示例
注:本文由純淨天空篩選整理自 Python iter()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。