持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第5天,点击查看活动详情
在许多情况下,我们需要像迭代器一样访问对象。一种方法是形成一个生成器循环,但这会延长程序员的任务和时间。Python通过为此任务提供内置方法__iter__()来简化此任务。
iter()函数返回给定对象(数组、集合、元组等或自定义对象)的迭代器。它创建一个对象,可以使用 next() 函数一次访问一个元素,这在处理循环时通常派上用场。
语法:
iter(object)
iter(callable, sentinel)
- 对象: 必须创建其迭代器的对象。它可以是集合对象(如列表或元组),也可以是用户定义的对象(使用 OOPS)。
- Callable, Sentinel:可调用表示可调用对象,哨兵是需要终止迭代的值,哨兵值表示迭代序列的结束。
例外:
如果我们在所有元素都具有之后调用迭代器已迭代,则引发停止迭代错误。
__iter__()
函数返回一个迭代器对象,该对象遍历给定对象的每个元素。下一个元素可以通过__next__()
函数访问。对于可调用的对象和哨兵值,将完成迭代,直到找到该值或到达元素的末尾。在任何情况下,都不会修改原始对象。
代码 #1 :
# 演示 iter() 基本用法的 Python 代码
listA = ['a','e','i','o','u']
iter_listA = iter(listA)
try:
print( next(iter_listA))
print( next(iter_listA))
print( next(iter_listA))
print( next(iter_listA))
print( next(iter_listA))
print( next(iter_listA)) #StopIteration error
except:
pass
输出:
a
e
i
o
u
代码 #2 :
# 演示 iter() 基本用法的 Python 代码
lst = [11, 22, 33, 44, 55]
iter_lst = iter(lst)
while True:
try:
print(iter_lst.__next__())
except:
break
输出:
11
22
33
44
55
代码 #3 :
# 演示 iter() 基本用法的 Python 代码
listB = ['Cat', 'Bat', 'Sat', 'Mat']
iter_listB = listB.__iter__()
try:
print(iter_listB.__next__())
print(iter_listB.__next__())
print(iter_listB.__next__())
print(iter_listB.__next__())
print(iter_listB.__next__()) #StopIteration error
except:
print(" \nThrowing 'StopIterationError'",
"I cannot count more.")
输出:
Cat
Bat
Sat
Mat
Throwing 'StopIterationError' I cannot count more.
代码 #4 : 用户定义的对象(使用 OOPS)
# 显示使用 OOPs 的迭代器() 的 Python 代码
class Counter:
def __init__(self, start, end):
self.num = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.num > self.end:
raise StopIteration
else:
self.num += 1
return self.num - 1
# 驱动代码
if __name__ == '__main__' :
a, b = 2, 5
c1 = Counter(a, b)
c2 = Counter(a, b)
# 方式 1-打印范围而不使用 iter()
print ("Print the range without iter()")
for i in c1:
print ("Eating more Pizzas, counting ", i, end ="\n")
print ("\nPrint the range using iter()\n")
当引发停止网站时,打印自定义消息
# 方式 2- 使用 iter()
obj = iter(c2)
try:
while True: # Print till error raised
print ("Eating more Pizzas, counting ", next(obj))
except:
# 当引发停止网站时,打印自定义消息
print ("\nDead on overfood, GAME OVER")
输出
Print the range without iter()
Eating more Pizzas, counting 2
Eating more Pizzas, counting 3
Eating more Pizzas, counting 4
Eating more Pizzas, counting 5
Print the range using iter()
Eating more Pizzas, counting 2
Eating more Pizzas, counting 3
Eating more Pizzas, counting 4
Eating more Pizzas, counting 5
Dead on overfood, GAME OVER