Python迭代器有has_next方法吗?
当前回答
除了所有提到的StopIteration, Python的“for”循环只是做你想要的:
>>> it = iter("hello")
>>> for i in it:
... print i
...
h
e
l
l
o
其他回答
不,没有这样的方法。迭代的结束由异常表示。请参见文档。
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。 请参阅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()
引导我进行搜索的用例如下
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”检查,以查看是否需要引发异常。然后,这个内部检查被隐藏起来,因此需要通过尝试获取一个项、捕捉异常并在抛出异常时运行处理程序来测试它。在我看来,这是不必要的隐藏。
也许只有我这么想,但虽然我喜欢https://stackoverflow.com/users/95810/alex-martelli的答案,但我发现这个更容易读:
from collections.abc import Iterator # since python 3.3 Iterator is here
class MyIterator(Iterator): # need to subclass Iterator rather than object
def __init__(self, it):
self._iter = iter(it)
self._sentinel = object()
self._next = next(self._iter, self._sentinel)
def __iter__(self):
return self
def __next__(self): # __next__ vs next in python 2
if not self.has_next():
next(self._iter) # raises StopIteration
val = self._next
self._next = next(self._iter, self._sentinel)
return val
def has_next(self):
return self._next is not self._sentinel
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获得所有直接子目录