如何在 Python 中压缩并填充到最长长度
在 Python 中,zip() 函数用于组合两个元素或更多可迭代对象。但是,zip() 只考虑最短输入的长度。如果你想将结果填充到最长输入的长度怎么办?
itertools.zip_longest
在Python 3中,itertools.zip_longest()函数提供了这个功能。它需要多个可迭代对象并返回一个迭代器,该迭代器生成包含可迭代对象中的元素的元组,其中 None 值填充较短的可迭代对象。
import itertools a = ['a1'] b = ['b1', 'b2', 'b3'] c = ['c1', 'c2'] result = list(itertools.zip_longest(a, b, c)) print(result) # Output: [('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
fillvalue 参数
您可以指定要使用的 fillvalue 参数,而不是 None
result = list(itertools.zip_longest(a, b, c, fillvalue='foo')) print(result) # Output: [('a1', 'b1', 'c1'), ('foo', 'b2', 'c2'), ('foo', 'b3', 'foo')]
Python 2 替代方案
对于 Python 2,您有两个选项:
result = map(None, a, b, c) print(list(result)) # Output: [('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
from itertools import izip_longest result = list(izip_longest(a, b, c)) print(result) # Output: [('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
以上是如何将 Python zip() 的结果填充到最长输入的长度?的详细内容。更多信息请关注PHP中文网其他相关文章!