How to Zip and Pad to the Longest Length in Python
In Python, the zip() function is used to combine elements from two or more iterable objects. However, zip() only considers the length of the shortest input. What if you want to pad the results to the length of the longest input?
itertools.zip_longest
In Python 3, the itertools.zip_longest() function provides this functionality. It takes multiple iterables and returns an iterator that yields tuples containing elements from the iterables, with None values padding the shorter iterables.
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 Parameter
You can specify a fillvalue parameter to use instead of None for padding.
result = list(itertools.zip_longest(a, b, c, fillvalue='foo')) print(result) # Output: [('a1', 'b1', 'c1'), ('foo', 'b2', 'c2'), ('foo', 'b3', 'foo')]
Python 2 Alternatives
For Python 2, you have two options:
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)]
The above is the detailed content of How to Pad the Results of Python\'s zip() to the Length of the Longest Input?. For more information, please follow other related articles on the PHP Chinese website!