初学python3,简单总结一下iter函数的用法。输出iter函数的__doc__可以看到如下内容:
iter(iterable) -> iterator
iter(callable, sentinel) -> iterator
iter(callable, sentinel) -> iterator
Get an iterator from an object. In the first form, the argument must
supply its own iterator, or be a sequence.
In the second form, the callable is called until it returns the sentinel.
supply its own iterator, or be a sequence.
In the second form, the callable is called until it returns the sentinel.
从这段话中我们可以看出,iter函数有两个用法,第一个是带入一个可迭代的对象,例如列表,然后该函数将返回一个迭代器。例如
print(list(iter('abcdefg')))#['a', 'b', 'c', 'd', 'e', 'f', 'g']
myiter = iter([1, 2, 3, 4, 5])
print(next(myiter)) #next()函数的使用# 1而第二种方法则是传入一个可调用的对象进行迭代,直到遇到“哨兵”。这句话可以理解为迭代器反复对一个函数进行调用,直到函数的返回值和iter函数的第二个参数相同时停止迭代。例如
i = 0
def iter_func():
global i
i = i + 1
return i
print(list(iter(iter_func, 10)))
#[1, 2, 3, 4, 5, 6, 7, 8, 9]
这种方法可以不用预先定义一个序列,而是通过函数逐步进行迭代。