[Python] zip_longest without fillvalue

Discussão em 'Python' iniciado por Stack, Junho 29, 2025.

  1. Stack

    Stack Membro Participativo

    I am searching for a middle ground between Python's zip and zip_longest functions (from the itertools module), that exhausts all given iterators, but does not fill in anything. So, for example, it should transpose tuples like so:

    (11, 12, 13 ), (11, 21, 31, 41),
    (21, 22, 23, 24), --> (12, 22, 32, 42),
    (31, 32 ), (13, 23, 43),
    (41, 42, 43, 44), ( 24, 44)


    (Spaces added for nicer graphical alignment.)

    I managed to compose a crude a solution by cleaning out the fillvalues after zip_longest.

    def zip_discard(*iterables, sentinel = object()):
    return map(
    partial(filter, partial(is_not, sentinel)),
    zip_longest(*iterables, fillvalue=sentinel))


    Is there a way to do this without introducing the sentinels to begin with? Can this be improved using yield? Which approach seems most efficient?

    Continue reading...

Compartilhe esta Página