Home > Backend Development > Python Tutorial > How to Pad the Results of Python\'s zip() to the Length of the Longest Input?

How to Pad the Results of Python\'s zip() to the Length of the Longest Input?

Susan Sarandon
Release: 2024-11-28 21:05:11
Original
748 people have browsed it

How to Pad the Results of Python's zip() to the Length of the Longest Input?

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

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

Python 2 Alternatives

For Python 2, you have two options:

  1. map(None, ...): This Python 2-specific feature of map can achieve the same result as zip_longest().
result = map(None, a, b, c)
print(list(result))
# Output: [('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
Copy after login
  1. itertools.izip_longest: This function was introduced in Python 2.6 and provides the same functionality as zip_longest().
from itertools import izip_longest

result = list(izip_longest(a, b, c))
print(result)
# Output: [('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
Copy after login

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!

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