Python迭代器有has_next方法吗?
当前回答
建议的方法是StopIteration。 请参阅tutorialspoint中的斐波那契示例
#!usr/bin/python3
import sys
def fibonacci(n): #generator function
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(5) #f is iterator object
while True:
try:
print (next(f), end=" ")
except StopIteration:
sys.exit()
其他回答
hasNext在某种程度上转换为StopIteration异常,例如:
>>> it = iter("hello")
>>> it.next()
'h'
>>> it.next()
'e'
>>> it.next()
'l'
>>> it.next()
'l'
>>> it.next()
'o'
>>> it.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
StopIteration文档:http://docs.python.org/library/exceptions.html#exceptions.StopIteration 一些关于python中的迭代器和生成器的文章:http://www.ibm.com/developerworks/library/l-pycon.html
不。最类似的概念很可能是StopIteration异常。
除了所有提到的StopIteration, Python的“for”循环只是做你想要的:
>>> it = iter("hello")
>>> for i in it:
... print i
...
h
e
l
l
o
引导我进行搜索的用例如下
def setfrom(self,f):
"""Set from iterable f"""
fi = iter(f)
for i in range(self.n):
try:
x = next(fi)
except StopIteration:
fi = iter(f)
x = next(fi)
self.a[i] = x
hasnext()在哪里可用
def setfrom(self,f):
"""Set from iterable f"""
fi = iter(f)
for i in range(self.n):
if not hasnext(fi):
fi = iter(f) # restart
self.a[i] = next(fi)
这对我来说更干净。显然,您可以通过定义实用程序类来解决这些问题,但接下来的情况是,您有20多种几乎等效的解决方法,每种方法都有各自的怪癖,如果您希望重用使用不同解决方法的代码,那么您必须在单个应用程序中有多个几乎等效的代码,或者四处挑选并重写代码以使用相同的方法。“只做一次,就把它做好”的格言很失败。
此外,迭代器本身需要有一个内部的“hasnext”检查,以查看是否需要引发异常。然后,这个内部检查被隐藏起来,因此需要通过尝试获取一个项、捕捉异常并在抛出异常时运行处理程序来测试它。在我看来,这是不必要的隐藏。
为了读取所有迭代,基于处理“StopIteration”执行的解决方法非常简单:
end_cursor = False
while not end_cursor:
try:
print(cursor.next())
except StopIteration:
print('end loop')
end_cursor = True
except:
print('other exceptions to manage')
end_cursor = True
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录