Python迭代器有has_next方法吗?


当前回答

为了读取所有迭代,基于处理“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

其他回答

为了读取所有迭代,基于处理“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

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

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

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

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

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

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