2014-10-06 53 views
3

我需要在Python從itertools效仿izip_longest 2.4我可以使用,而不是下一個()在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 

一切工作正常,直到我到達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()相同的結果?

+0

出於好奇,你爲什麼要使用一個類具有靜態方法?爲什麼不只是做一個功能呢? – 2014-10-06 13:59:57

+0

有點相關(不完全重複):http://stackoverflow.com/q/25810855/1639625 – 2014-10-06 14:00:23

回答

6

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 
+0

謝謝。現在它完美:) – BigZ 2014-10-06 14:00:24

相關問題