python中的next()以及iter()函数

我们首先要知道什么是可迭代的对象(可以用for循环的对象)Iterable:

一类:list,tuple,dict,set,str

二类:generator,包含生成器和带yield的generatoe function

而生成器不但可以作用于for,还可以被next()函数不断调用并返回下一个值,可以被next()函数不断返回下一个值的对象称为迭代器:Iterator

生成器都是Iterator对象,但list,dict,str是Iterable,但不是Iterator,要把list,dict,str等Iterable转换为Iterator可以使用iter()函数

next()用法:

next(iterator[, default])
iterator -- 可迭代对象
default -- 可选,用于设置在没有下一个元素时返回该默认值,如果不设置,又没有下一个元素则会触发 StopIteration 异常。
>>> list_ = [1,2,3,4,5]
>>> it = iter(list_)
>>> next(it,'-1')
1
>>> next(it,'-1')
2
>>> next(it,'-1')
3
>>> next(it,'-1')
4
>>> next(it,'-1')
5
>>> next(it,'-1')
'-1'
---------------------
作者:阿_波_
来源:CSDN
原文:https://blog.csdn.net/li1615882553/article/details/79360172
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自www.cnblogs.com/jfdwd/p/10963475.html