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
Release: 2024-11-26 10:49:09
Original
224 people have browsed it

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)]
Copy after login

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')]
Copy after login

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)]
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template