Der*_*ang 201
有一个替代StopIteration
使用next(iterator, default_value)
.
为了exapmle:
>>> a = iter('hi')
>>> print next(a, None)
h
>>> print next(a, None)
i
>>> print next(a, None)
None
Run Code Online (Sandbox Code Playgroud)
因此None
,如果不需要异常方式,则可以检测迭代器结尾的其他预先指定的值.
ava*_*kar 93
不,没有这样的方法.迭代的结束由异常指示.请参阅文档.
Ale*_*lli 36
如果你真的需要一个has-next
功能(因为你只是忠实地从Java中的参考实现转录的算法,说,还是因为你写一个原型,将需要轻松转录到Java的时候,它的完成),它很容易用一个小包装类获得它.例如:
class hn_wrapper(object):
def __init__(self, it):
self.it = iter(it)
self._hasnext = None
def __iter__(self): return self
def next(self):
if self._hasnext:
result = self._thenext
else:
result = next(self.it)
self._hasnext = None
return result
def hasnext(self):
if self._hasnext is None:
try: self._thenext = next(self.it)
except StopIteration: self._hasnext = False
else: self._hasnext = True
return self._hasnext
Run Code Online (Sandbox Code Playgroud)
现在像
x = hn_wrapper('ciao')
while x.hasnext(): print next(x)
Run Code Online (Sandbox Code Playgroud)
发射
c
i
a
o
Run Code Online (Sandbox Code Playgroud)
按要求.
请注意,使用next(sel.it)
内置需要Python 2.6或更高版本; 如果你使用的是旧版本的Python,请self.it.next()
改用(next(x)
在示例用法中类似).[[你可能会合理地认为这个说明是多余的,因为Python 2.6已经存在了一年多了 - 但是当我在回复中使用Python 2.6功能时,一些评论者或其他人认为有义务指出他们是 2.6的功能,因此我试图阻止这样的评论一次;-)]]
Bri*_*per 13
除了所有提到的StopIteration之外,Python"for"循环只是做你想要的:
>>> it = iter("hello")
>>> for i in it:
... print i
...
h
e
l
l
o
Run Code Online (Sandbox Code Playgroud)
从任何迭代器对象尝试__length_hint __()方法:
iter(...).__length_hint__() > 0
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
StopIteration
docs:http://docs.python.org/library/exceptions.html#exceptions.StopIteration 归档时间: |
|
查看次数: |
114666 次 |
最近记录: |