iter():此函数获取一个对象并返回与该参数对应的迭代器对象。
next():此函数使用迭代器并返回输入中的下一个元素。如果我们再次调用它,它会记住之前返回的值并输出下一个值。
看到了迭代器对象,那么就不得不看看魔术方法__iter__()了。只要内置有__iter__()方法的就可以称之为可迭代对象。可以转换为迭代器的对象,就称之为可迭代对象。
list_ = [1,2,3,4]
tuple_ = (1,2,3,4)
dict_ = {"name1":"清安","name2":"拾贰"}
list_.__iter__()
tuple_.__iter__()
dict_.__iter__()
列举了三个数据结构,都带有__iter__()方法。所以:
list_ = [1,2,3,4]
list_res = list_.__iter__()
print(list_res)
""""""
这个列表也就成功变成了一个迭代器。
def iter(source, sentinel=None): # known special case of iter"""iter(iterable) -> iteratoriter(callable, sentinel) -> iteratorGet an iterator from an object. In the first form, the argument mustsupply its own iterator, or be a sequence.In the second form, the callable is called until it returns the sentinel."""pass
def __iter__(self, *args, **kwargs): # real signature unknown""" Implement iter(self). """pass
本质作用都是一样的。将可迭代对象转为迭代器对象。所以可以这样写:
list_ = [1,2,3,4]
tuple_ = (1,2,3,4)
list_res = list_.__iter__()
print(list_res)
print(iter(tuple_))
"""
"""
list_ = [1,2,3,4]
print(next(list_))
这样会告诉你:TypeError: ‘list’ object is not an iterator,类型错误,列表对象不是迭代器。所以要想使用next()取值就必须先iter()。
list_ = [1,2,3,4]
res_list = iter(list_)
print(next(res_list))
print(next(res_list))
print(next(res_list))
print(next(res_list))
print(next(res_list))
取一次值就next一次,下一次使用next会接着上一次的位置取值。当超出后会告诉你:StopIteration停止迭代。
def next(iterator, default=None): # real signature unknown; restored from __doc__"""next(iterator[, default])Return the next item from the iterator. If default is given and the iteratoris exhausted, it is returned instead of raising StopIteration."""pass
list_ = [1,2,3,4]
res_list = iter(list_)
print(next(res_list))
print(res_list.__next__())
本质作用都是一样的,迭代取值。
迭代器就是一个重复取值的工具。那么while,for似乎都是类似的作用。
list_ = [1,2,3,4]
res_list = iter(list_)
while True:print(next(res_list))
这样就简化了每次都要写next的情况。但是依旧会抛出异常StopIteration。
list_ = [1,2,3,4]
for value in iter(list_):print(value)
而for循环却不会。要想while不抛出异常我们可以用try来捕捉异常达到预期的效果。至于for循环:

看到了吗,for循环本质就是使用了iter,所以即使不使用iter()直接使用for value in list_也是可以的。为什么不抛出异常,应为for循环以及帮我们做了对应的操作了。
上一篇:Unity计算着色器 02