Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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:

somezip(a, b) == [(1, 5), (2, 6), (3, 7), (4, 8)]
somezip(a, c) == [(1, 10), (2, 11), (3, 12), (4, None)]

Behaving somewhere between zip and zip_longest?

like image 822
Eric Avatar asked Nov 12 '12 09:11

Eric


People also ask

What is Zip_longest?

zip_longest() The built-in zip() function takes in multiple iterables as arguments and returns an iterator, which we can use to generate series of tuples consisting of elements in each iterable. It requires the input iterables to be of equal length.

Is Itertools built in Python?

Itertools is a module in Python, it is used to iterate over data structures that can be stepped over using a for-loop. Such data structures are also known as iterables. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra.


2 Answers

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)]
like image 124
Abhijit Avatar answered Sep 28 '22 11:09

Abhijit


import itertools as it

somezip = lambda *x: it.islice(it.izip_longest(*x), len(x[0]))



>>> list(somezip(a,b))
[(1, 5), (2, 6), (3, 7), (4, 8)]

>>> list(somezip(a,c))
[(1, 10), (2, 11), (3, 12), (4, None)]
like image 31
eumiro Avatar answered Sep 28 '22 13:09

eumiro