猿问

Python:拉链式的函数,它的长度是最长的吗?

Python:拉链式的函数,它的长度是最长的吗?

是否有一个内建函数可以像zip()但是,这将使结果列表的长度成为最长输入而不是最短输入?


>>> a=['a1']

>>> b=['b1','b2','b3']

>>> c=['c1','c2']


>>> zip(a,b,c)

[('a1', 'b1', 'c1')]


>>> What command goes here?

[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]


慕村9548890
浏览 529回答 3
3回答

慕勒3428872

对于Python2.6x使用itertools模块的izip_longest.对于Python 3使用zip_longest相反(没有领导)i).>>> list(itertools.izip_longest(a, b, c))[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]

绝地无双

非迭代工具Python 3解决方案:def zip_longest(*lists):     def g(l):         for item in l:             yield item        while True:             yield None     gens = [g(l) for l in lists]         for _ in range(max(map(len, lists))):         yield tuple(next(g) for g in gens)
随时随地看视频慕课网APP

相关分类

Python
我要回答