为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕村9548890 2019-07-10 16:22:50
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)]
查看完整描述

3 回答

?
慕勒3428872

TA贡献1848条经验 获得超6个赞

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


查看完整回答
反对 回复 2019-07-10
?
绝地无双

TA贡献1946条经验 获得超4个赞

非迭代工具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)


查看完整回答
反对 回复 2019-07-10
  • 3 回答
  • 0 关注
  • 528 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信