Extending zip() Functionality: Padding to Longest Length
Python's built-in zip() function pairs elements from multiple iterables, but it truncates the result to the length of the shortest iterable. If you require a more comprehensive zip that pads with None values to align with the longest input, consider the following solutions:
Python 3: itertools.zip_longest
In Python 3, itertools provides the zip_longest() function. It expands the result list to match the length of the longest input.
import itertools a = ['a1'] b = ['b1', 'b2', 'b3'] c = ['c1', 'c2'] list(itertools.zip_longest(a, b, c)) # [('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
You can specify a custom fill value 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 or map None
In Python 2, you can use itertools.izip_longest (introduced in Python 2.6) or employ map with None.
from itertools import izip_longest a = ['a1'] b = ['b1', 'b2', 'b3'] c = ['c1', 'c2'] list(izip_longest(a, b, c)) # [('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)] map(None, a, b, c) # [('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
The above is the detailed content of How Can I Extend Python\'s zip() Function to Handle Iterables of Unequal Lengths?. For more information, please follow other related articles on the PHP Chinese website!