Python迭代器有has_next方法吗?


当前回答

也许只有我这么想,但虽然我喜欢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

其他回答

不,没有这样的方法。迭代的结束由异常表示。请参见文档。

你可以使用itertools来tee迭代器。在teed迭代器上检查StopIteration。

我解决问题的方法是保留到目前为止迭代的对象数量的计数。我想通过调用实例方法遍历一个集合。因为我知道集合的长度,以及到目前为止计数的项的数量,所以我有效地使用了hasNext方法。

我的代码的一个简单版本:

class Iterator:
    # s is a string, say
    def __init__(self, s):
        self.s = set(list(s))
        self.done = False
        self.iter = iter(s)
        self.charCount = 0

    def next(self):
        if self.done:
            return None
        self.char = next(self.iter)
        self.charCount += 1
        self.done = (self.charCount < len(self.s))
        return self.char

    def hasMore(self):
        return not self.done

当然,这个例子是一个玩具,但您可以理解。这在无法获取可迭代对象长度的情况下不起作用,比如生成器等。

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

我相信python只有next(),根据文档,如果没有更多的元素,它就会抛出异常。

http://docs.python.org/library/stdtypes.html#iterator-types