2

当我next(ByteIter, '')<<8在 python 中做时,我得到一个名称错误说

“未定义全局名称‘下一个’”

我猜这个功能因为python版本而无法识别?我的版本是2.5。

4

3 回答 3

3

文档

下一个(迭代器 [,默认值])

Retrieve the next item from the iterator by calling its next() method. 
If default is given, it is returned if the iterator is
exhausted, otherwise StopIteration is raised.

New in version 2.6.

所以是的,它确实需要 2.6 版。

于 2013-04-25T21:19:17.057 回答
1

直到 Python 2.6 才添加该next()函数。

但是,有一种解决方法。您可以调用.next()Python 2 可迭代对象:

try:
    ByteIter.next() << 8
except StopIteration:
    pass

.next()抛出 aStopIteration并且您不能指定默认值,因此您需要StopIteration显式捕获。

可以将其包装在自己的函数中:

_sentinel = object()
def next(iterable, default=_sentinel):
    try:
        return iterable.next()
    except StopIteration:
        if default is _sentinel:
            raise
        return default

这就像 Python 2.6 版本一样工作:

>>> next(iter([]), 'stopped')
'stopped'
>>> next(iter([]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in next
StopIteration
于 2013-04-25T21:38:58.377 回答
1

尽管您可以在 2.6 中调用 ByteIter.next()。但是不建议这样做,因为该方法在 python 3 中已重命名为next ()。

于 2013-04-25T21:25:24.550 回答