【发布时间】:2013-04-19 22:43:23
【问题描述】:
当我在 python 中执行next(ByteIter, '')<<8 时,我得到一个名称错误提示
“未定义全局名称'next'”
我猜这个函数因为python版本而无法识别?我的版本是 2.5。
【问题讨论】:
当我在 python 中执行next(ByteIter, '')<<8 时,我得到一个名称错误提示
“未定义全局名称'next'”
我猜这个函数因为python版本而无法识别?我的版本是 2.5。
【问题讨论】:
来自the docs
下一个(迭代器[,默认])
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 版。
【讨论】:
虽然您可以在 2.6 中调用 ByteIter.next()。但是不建议这样做,因为该方法在 python 3 中已重命名为 next()。
【讨论】:
next() function 直到 Python 2.6 才添加。
不过,有一种解决方法。您可以在 Python 2 可迭代对象上调用 .next():
try:
ByteIter.next() << 8
except StopIteration:
pass
.next() 抛出 StopIteration 并且您无法指定默认值,因此您需要显式捕获 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
【讨论】: