2013-04-25 28 views
2

当我在Python做next(ByteIter, '')<<8,我有名字错误说的Python:下一个()无法识别

“全局名称‘下一步’没有定义”

我猜这个函数由于Python版本而不被识别?我的版本是2.5。

+0

它在py2.6 HTTP介绍://文档。 python.org/2/library/functions.html#next – 2013-04-25 21:19:22

回答

3

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版。

1

虽然你可以在2.6中调用ByteIter.next()。不过不推荐这样做,因为该方法已在python 3中重命名为下一个()。

1

next() function直到Python 2.6才被添加。

但是,有一种解决方法。您可以在Python的2 iterables拨打.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