Python built-in functions (36) -- iter, python built-in 36 iter
English document:
iter(Object[,Sentinel])
Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument,ObjectMust be a collection object which supports the iteration protocol (__iter__()Method), or it must support the sequence protocol (__getitem__()Method with integer arguments starting0). If it does not support either of those protocols,TypeErrorIs raised. If the second argument,Sentinel, Is given, thenObjectMust be a callable object. The iterator created in this case will callObjectWith no arguments for each call to its__next__()Method; if the value returned is equalSentinel,StopIterationWill be raised, otherwise the value will be returned.
One useful application of the second formiter()Is to read lines of a file until a certain line is reached. The following example reads a file untilreadline()Method returns an empty string:
with open('mydata.txt') as fp: for line in iter(fp.readline, ''): process_line(line)
Note:
1. The function returns an iteratable object.
2. when the second parameter is not provided, the first parameter must be an iterative protocol (that is, the _ iter _ () method is implemented) (Dictionary, set, and immutable set), or support the sequence protocol (that is, the _ getitem _ () method is implemented to receive an integer parameter starting from 0). Otherwise, an error is returned.
>>> A = iter ({'A': 1, 'B': 2 }) # dictionary set >>> a <dict_keyiterator object at 0x03FB8A50 >>>> next (a) 'A' >>> next (A) 'B' >>> next () traceback (most recent call last): File "<pyshell #36>", line 1, in <module> next (a) StopIteration> a = iter ('abcd ') # string sequence >>> a <str_iterator object at 0x03FB4FB0 >>>> next (a) 'A' >>>> next (a) 'B' >>> next () 'C' >>>> next (a) 'd >>>> next (a) Traceback (most recent call last): File "<pyshell #29>", line 1, in <module> next (a) StopIteration
3. When the second parameterSentinelWhen provided, the first parameter must be a callable object. This callable object is called when the _ next _ method is called.SentinelIf the value is equalStopIteration exception. Terminate iteration.
# Define class >>> class IterTest: def _ init _ (self): self. start = 0 self. end = 10 def get_next_value (self): current = self. start if current <self. end: self. start + = 1 else: raise StopIteration return current >>> iterTest = IterTest () # instantiate class >>> a = iter (iterTest. get_next_value, 4) # iterTest. get_next_value is a callable object, and the sentinel value is 4 >>> a <callable_iterator object at 0x03078D30 >>> next (a) 0 >>> next () 1 >>> next (a) 2 >>> next (a) 3 >>> next (a) # iteration to 4 terminate Traceback (most recent call last ): file "<pyshell #22>", line 1, in <module> next (a) StopIteration