Python迭代器有has_next方法吗?


当前回答

使用next(迭代器,default_value)可以替代StopIteration。

For exapmle:

>>> a = iter('hi')
>>> print next(a, None)
h
>>> print next(a, None)
i
>>> print next(a, None)
None

因此,如果你不想用异常方式,你可以为None或其他预先指定的值检测迭代器的end。

其他回答

不,没有这样的方法。迭代的结束是由StopIteration表示的(更多信息在这里)。


这遵循了python原则EAFP(请求原谅比请求许可更容易)。has_next方法将遵循LBYL原则(三思而后行),并与python的核心原则相矛盾。

这篇有趣的文章更详细地解释了这两个概念。

使用next(迭代器,default_value)可以替代StopIteration。

For exapmle:

>>> a = iter('hi')
>>> print next(a, None)
h
>>> print next(a, None)
i
>>> print next(a, None)
None

因此,如果你不想用异常方式,你可以为None或其他预先指定的值检测迭代器的end。

使用“for”可以实现他自己版本的“next”避免异常

def my_next(it):
    for x in it:
        return x
    return None

不。最类似的概念很可能是StopIteration异常。

如果您确实需要一个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