Home >Backend Development >Python Tutorial >How Can I Pad Python\'s Zip Function to the Length of the Longest Iterable?

How Can I Pad Python\'s Zip Function to the Length of the Longest Iterable?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-26 10:49:09294browse

How Can I Pad Python's Zip Function to the Length of the Longest Iterable?

Extending Zip to Pad to Maximum Length

Zip is a built-in function in Python that combines multiple iterables. However, it stops at the length of the shortest iterable. What if we want to pad the results to match the length of the longest iterable?

Solution

In Python 3, itertools.zip_longest provides this functionality. It evaluates all iterables and pads with None by default, maintaining the alignment.

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 customize the padding value using the fillvalue parameter:

list(itertools.zip_longest(a, b, c, fillvalue='foo'))

# [('a1', 'b1', 'c1'), ('foo', 'b2', 'c2'), ('foo', 'b3', 'foo')]

For Python 2, you can use itertools.izip_longest (Python 2.6 ) or map with None:

a = ['a1']
b = ['b1', 'b2', 'b3']
c = ['c1', 'c2']

map(None, a, b, c)

# [('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]

The above is the detailed content of How Can I Pad Python\'s Zip Function to the Length of the Longest Iterable?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn