【问题标题】:Python: next() is not recognizedPython:next() 无法识别
【发布时间】:2013-04-19 22:43:23
【问题描述】:

当我在 python 中执行next(ByteIter, '')<<8 时,我得到一个名称错误提示

“未定义全局名称'next'”

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

【问题讨论】:

标签: python next


【解决方案1】:

来自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】:

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

    【讨论】:

      【解决方案3】:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-11
        • 1970-01-01
        • 1970-01-01
        • 2018-06-18
        • 2019-01-28
        • 2017-08-10
        • 2019-11-01
        • 2015-08-14
        相关资源
        最近更新 更多