2013-04-25 33 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