【问题标题】:What could I use instead of next() in python 2.4在 python 2.4 中我可以用什么代替 next()
【发布时间】:2014-11-30 19:17:20
【问题描述】:

我需要在 Python 2.4 中从 itertools 模拟 izip_longest

import itertools
class Tools:
    @staticmethod
    def izip_longest(*args, **kwds):
        # izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
        fillvalue = kwds.get('fillvalue')
        counter = [len(args) - 1]
        def sentinel():
            if not counter[0]:
                raise ZipExhausted
            counter[0] -= 1
            yield fillvalue
        fillers = itertools.repeat(fillvalue)
        iterators = [itertools.chain(it, sentinel(), fillers) for it in args]
        try:
        while iterators:
            yield tuple(map(next, iterators))
        except ZipExhausted:
            pass       


class ZipExhausted(Exception):
    pass

一切正常,直到我到达yield tuple(map(next, iterators)); Python 2.4 抛出了一个

NameError: global name 'next' is not defined

错误并退出。

我可以用什么来代替next 使izip_longest 在Python 2.4 中运行?

或者 Python 2.4 中是否有任何其他函数返回与 izip_longest() 相同的结果?

【问题讨论】:

  • 出于好奇,您为什么要使用具有静态方法的类?为什么不把它变成一个函数呢?
  • 有些相关(不完全重复):stackoverflow.com/q/25810855/1639625

标签: python next itertools python-2.4


【解决方案1】:

next() function 已添加到 Python 2.6。改用迭代器中的next 方法:

while iterators:
    yield tuple([it.next() for it in iterators])

或者定义你自己的next()函数;你没有使用 default 参数,所以对于你更简单的情况是:

def next(it):
    return it.next()

但完整版是:

_sentinel = object()

def next(it, default=_sentinel):
    try:
        return it.next()
    except StopIteration:
        if default is _sentinel:
            raise
        return default

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多