python – `zip`和`zip_longest`之间是否存在中间立场

说我有这三个列表:

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)]

表现在zip和zip_longest之间?

最佳答案
没有,但你可以轻松地结合takewhileizip_longest的功能来实现你想要的

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

(如果第一个迭代器可能包含计算结果为False的项,则可以用lambda表达式替换itemgetter – 请参阅@ ovgolovin的注释)

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

例子

>>> 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)]

转载注明原文:python – `zip`和`zip_longest`之间是否存在中间立场 - 代码日志