我可以在python 2.4中使用什么而不是next()

Big*_*igZ 3 python python-2.4 next python-itertools

我需要模拟izip_longestitertools在Python 2.4

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
Run Code Online (Sandbox Code Playgroud)

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

NameError: global name 'next' is not defined
Run Code Online (Sandbox Code Playgroud)

错误并退出.

我可以使用,而不是next使izip_longest运行在Python 2.4?

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

Mar*_*ers 6

next()函数已添加到Python 2.6中.使用next迭代器中的方法:

while iterators:
    yield tuple([it.next() for it in iterators])
Run Code Online (Sandbox Code Playgroud)

或定义自己的next()功能; 你没有使用这个default论点,所以对于你的简单案例来说:

def next(it):
    return it.next()
Run Code Online (Sandbox Code Playgroud)

但完整版将是:

_sentinel = object()

def next(it, default=_sentinel):
    try:
        return it.next()
    except StopIteration:
        if default is _sentinel:
            raise
        return default
Run Code Online (Sandbox Code Playgroud)