在许多情况下, 我们需要访问类似迭代器的对象。一种方法是形成生成器循环, 但这会延长程序员的工作量和时间。 Python通过提供内置方法来简化此任务__iter __()为此任务。
__iter __()函数返回给定对象(数组, 集合, 元组等或自定义对象)的迭代器。它创建一个对象, 该对象可以使用一次访问一个元素__next__()函数, 通常在处理循环时会派上用场。
句法 :
iter(object)
iter(callable, sentinel)
- 对象:必须创建其迭代器的对象。它可以是列表或元组之类的集合对象, 也可以是用户定义的对象(使用OOPS)。
- 可致电, 前哨:Callable表示可调用的对象, 并且sentinel是需要终止迭代的值, sentinel值表示要迭代的序列的末尾。
例外情况:
If we call the iterator after all the elements have
been iterated, then StopIterationError is raised.
__iter __()函数返回遍历给定对象的每个元素的迭代器对象。可以通过__next __()函数访问下一个元素。对于可调用对象和前哨值, 将进行迭代直到找到该值或到达元素的末尾。无论如何, 原始对象都不会被修改。
代码1:
# Python code demonstrating
# basic use of iter()
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:
# Python code demonstrating
# basic use of iter()
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:
# Python code demonstrating
# basic use of iter()
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)
# Python code showing use of iter() using OOPs
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
# Driver code
if __name__ = = '__main__' :
a, b = 2 , 5
c1 = Counter(a, b)
c2 = Counter(a, b)
# Way 1-to print the range without iter()
print ( "Print the range without iter()" )
for i in c1:
print ( "Eating more Pizzas, couting " , i, end = "\n" )
print ( "\nPrint the range using iter()\n" )
# Way 2- using iter()
obj = iter (c2)
try :
while True : # Print till error raised
print ( "Eating more Pizzas, couting " , next (obj))
except :
# when StopIteration raised, Print custom message
print ( "\nDead on overfood, GAME OVER" )
输出:
Print the range without iter()
Eating more Pizzas, couting 2
Eating more Pizzas, couting 3
Eating more Pizzas, couting 4
Eating more Pizzas, couting 5
Print the range using iter()
Eating more Pizzas, couting 2
Eating more Pizzas, couting 3
Eating more Pizzas, couting 4
Eating more Pizzas, couting 5
Dead on overfood, GAME OVER
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。
来源:
https://www.srcmini02.com/70544.html