Python迭代器有has_next方法吗?
当前回答
我相信python只有next(),根据文档,如果没有更多的元素,它就会抛出异常。
http://docs.python.org/library/stdtypes.html#iterator-types
其他回答
除了所有提到的StopIteration, Python的“for”循环只是做你想要的:
>>> it = iter("hello")
>>> for i in it:
... print i
...
h
e
l
l
o
不。最类似的概念很可能是StopIteration异常。
不,没有这样的方法。迭代的结束由异常表示。请参见文档。
为了读取所有迭代,基于处理“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
如果您确实需要一个has-next功能,那么使用一个小包装器类很容易获得它。例如:
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
现在就像
x = hn_wrapper('ciao')
while x.hasnext(): print next(x)
发出
c
i
a
o
是必需的。
Note that the use of next(sel.it) as a built-in requires Python 2.6 or better; if you're using an older version of Python, use self.it.next() instead (and similarly for next(x) in the example usage). [[You might reasonably think this note is redundant, since Python 2.6 has been around for over a year now -- but more often than not when I use Python 2.6 features in a response, some commenter or other feels duty-bound to point out that they are 2.6 features, thus I'm trying to forestall such comments for once;-)]]
===
对于Python3,您将进行以下更改:
from collections.abc import Iterator # since python 3.3 Iterator is here
class hn_wrapper(Iterator): # need to subclass Iterator rather than object
def __init__(self, it):
self.it = iter(it)
self._hasnext = None
def __iter__(self):
return self
def __next__(self): # __next__ vs next in python 2
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
推荐文章
- 在python中遍历对象属性
- 如何在Python中使用方法重载?
- 在Python中提取文件路径(目录)的一部分
- 如何安装没有根访问权限的python模块?
- 尝试模拟datetime.date.today(),但不工作
- 将行添加到数组
- 如何在Python中直接获得字典键作为变量(而不是通过从值搜索)?
- Python:为什么functools。部分有必要吗?
- 如何用python timeit对代码段进行性能测试?
- Python迭代器中的has_next ?
- ConfigParser中的列表
- 由于环境错误无法安装包:[Errno 13]
- 如何测试一个字符串是否包含列表中的一个子字符串,在熊猫?
- 'datetime'模块没有'strptime'属性
- 如何将字典保存到文件?