是否有类似拉链的功能可以垫到最长的长度? [英] Is there a zip-like function that pads to longest length?
问题描述
是否有像 zip() 这样的内置函数
但这会填充结果,因此结果列表的长度是最长输入的长度,而不是最短输入的长度?
在 Python 3 中你可以使用 itertools.zip_longest
您可以使用 fillvalue
参数填充与 None
不同的值:
使用 Python 2,您可以使用 itertools.izip_longest
(Python 2.6+),或者你可以使用 map
和 None
.这是一个鲜为人知的map
的功能(但 map
在 Python 3.x 中发生了变化,所以这只适用于 Python 2.x).
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)]
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)]
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')]
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)]
这篇关于是否有类似拉链的功能可以垫到最长的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!