Outerzip / zip longest function (with multiple fill values)

前端 未结 3 1949
有刺的猬
有刺的猬 2021-01-11 17:19

Is there a Python function an \"outer-zip\", which is a extension of zip with different default values for each iterable?

a = [1, 2, 3]   # associate a defa         


        
3条回答
  •  难免孤独
    2021-01-11 17:50

    You could modify zip_longest to support your use case for general iterables.

    from itertools import chain, repeat
    
    class OuterZipStopIteration(Exception):
        pass
    
    def outer_zip(*args):
        count = len(args) - 1
    
        def sentinel(default):
            nonlocal count
            if not count:
                raise OuterZipStopIteration
            count -= 1
            yield default
    
        iters = [chain(p, sentinel(default), repeat(default)) for p, default in args]
        try:
            while iters:
                yield tuple(map(next, iters))
        except OuterZipStopIteration:
            pass
    
    
    print(list(outer_zip( ("abcd", '!'), 
                          ("ef", '@'), 
                          (map(int, '345'), '$') )))
    

提交回复
热议问题