zip_longest without fillvalue

前端 未结 2 816
南旧
南旧 2020-12-07 01:01

I am searching for a middle ground between Python\'s zip and zip_longest functions (from the itertools module), that exhausts all given

2条回答
  •  日久生厌
    2020-12-07 01:29

    Both zip and zip_longest were designed to always generate tuples of equal length, you can define your own generator that doesn't care about the len with something like this:

    def _one_pass(iters):
        for it in iters:
            try:
                yield next(it)
            except StopIteration:
                pass #of some of them are already exhausted then ignore it.
    
    def zip_varlen(*iterables):
        iters = [iter(it) for it in iterables]
        while True: #broken when an empty tuple is given by _one_pass
            val = tuple(_one_pass(iters))
            if val:
                yield val
            else:
                break
    

    If the data being zipped together is fairly large then skipping the exhausted iterators every time can be expensive, it may be more efficient to remove the finished iterators from iters in the _one_pass function like this:

    def _one_pass(iters):
        i = 0
        while i

    both of these versions would remove the need to create intermediate results or use temporary filler values.

提交回复
热议问题