是否有可拉长最长长度的类似zip的功能? [英] Is there a zip-like function that pads to longest length?

查看:29
本文介绍了是否有可拉长最长长度的类似zip的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个内置函数,其功能类似于 zip() ,但这将填充结果,以便结果列表的长度是最长输入的长度,而不是最短输入的长度?

Is there a built-in function that works like zip() but that will pad the results so that the length of the resultant list is the length of the longest input rather than the shortest input?

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

推荐答案

在Python 3中,您可以使用 itertools.zip_longest

In Python 3 you can use itertools.zip_longest

>>> list(itertools.zip_longest(a, b, c))
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]

您可以使用 fillvalue 参数用不同于 None 的值填充:

You can pad with a different value than None by using the fillvalue parameter:

>>> list(itertools.zip_longest(a, b, c, fillvalue='foo'))
[('a1', 'b1', 'c1'), ('foo', 'b2', 'c2'), ('foo', 'b3', 'foo')]

使用Python 2,您可以使用 itertools.izip_longest (Python 2.6+),也可以将 map None 结合使用.这是一个鲜为人知的 map 的功能(但 map 在Python 3.x中已更改,因此仅在Python 2.x中有效).

With Python 2 you can either use itertools.izip_longest (Python 2.6+), or you can use map with None. It is a little known feature of map (but map changed in Python 3.x, so this only works in Python 2.x).

>>> map(None, a, b, c)
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]

这篇关于是否有可拉长最长长度的类似zip的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆