Is there a middle ground between `zip` and `zip_longest`

前端 未结 5 1058
面向向阳花
面向向阳花 2021-01-12 11:54

Say I have these three lists:

a = [1, 2, 3, 4]
b = [5, 6, 7, 8, 9]
c = [10, 11, 12]

Is there a builtin function such that:

         


        
5条回答
  •  佛祖请我去吃肉
    2021-01-12 12:39

    No there isn't, but you can easily combine the functionality of takewhile and izip_longest to achieve what you want

    from itertools import takewhile, izip_longest
    from operator import itemgetter
    somezip = lambda *p: list(takewhile(itemgetter(0),izip_longest(*p)))
    

    (In case the first-iterator may have items which evaluates to False, you can replace the itemgetter with a lambda expression - refer @ovgolovin's comment)

    somezip = lambda *p: list(takewhile(lambda e: not e[0] is None,izip_longest(*p)))
    

    Examples

    >>> from itertools import takewhile, izip_longest
    >>> from operator import itemgetter
    >>> a = [1, 2, 3, 4]
    >>> b = [5, 6, 7, 8, 9]
    >>> c = [10, 11, 12]
    >>> somezip(a,b)
    [(1, 5), (2, 6), (3, 7), (4, 8)]
    >>> somezip(a,c)
    [(1, 10), (2, 11), (3, 12), (4, None)]
    >>> somezip(b,c)
    [(5, 10), (6, 11), (7, 12), (8, None), (9, None)]
    

提交回复
热议问题