2

next(ByteIter, '')<<8Pythonで行うと、名前エラーが発生しました

「グローバル名 'next' は定義されていません」

Pythonのバージョンが原因で、この機能が認識されていないと思いますか?私のバージョンは2.5です。

4

3 に答える 3

3

ドキュメントから

next(イテレータ[, デフォルト])

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

next()関数は Python 2.6 まで追加されませんでした。

ただし、回避策があります。.next()Python 2 iterables で呼び出すことができます:

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
于 2013-04-25T21:38:58.377 に答える