首頁 >後端開發 >Python教學 >如何將 Python 的 Zip 函數填入最長可迭代的長度?

如何將 Python 的 Zip 函數填入最長可迭代的長度?

Patricia Arquette
Patricia Arquette原創
2024-11-26 10:49:09317瀏覽

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

將 Zip 擴展到 Pad 至最大長度

Zip 是 Python 中的一個內建函數,它組合了多個可迭代物件。但是,它會停在最短可迭代的長度。如果我們想要填充結果以匹配最長可迭代的長度怎麼辦?

解決方案

在 Python 3 中,itertools.zip_longest 提供了此功能。預設情況下,它使用 None 評估所有迭代和填充,保持對齊。

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)]

您可以使用fillvalue 參數自訂填充值:

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

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

對於Python 2,您可以使用itertools.izip_longest (Python 2.6 ) 或使用None 進行映射:

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

map(None, a, b, c)

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

以上是如何將 Python 的 Zip 函數填入最長可迭代的長度?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn