Python的Itertool是提供各種函數,關於迭代器的工作產生複雜的迭代器的模塊。這個模塊作為其或者使用本身或組合使用以形成迭代代數快速,存儲器高效工具。
在Python迭代器是一個對象,可以迭代樣序列數據類型,如列表,元組,STR等。
注意:有關更多信息,請參閱Python Itertools。
Itertools.zip_longest()
這個迭代器屬於終止迭代器的範疇。它交替打印可迭代值。如果iterables中的一個被完全印刷,剩餘的值由分配給值填充fillvalue
參數。
用法:
zip_longest( iterable1, iterable2, fillval)
範例1:
# Python code to demonstrate the working of
# zip_longest()
import itertools
# using zip_longest() to combine two iterables.
print ("The combined values of iterables is :")
print (*(itertools.zip_longest('GesoGes', 'ekfrek', fillvalue ='_' )))
輸出:
The combined values of iterables is : ('G', 'e') ('e', 'k') ('s', 'f') ('o', 'r') ('G', 'e') ('e', 'k') ('s', '_')
範例2:
from itertools import zip_longest
x =[1, 2, 3, 4, 5, 6, 7]
y =[8, 9, 10]
z = list(zip_longest(x, y))
print(z)
輸出:
[(1, 8), (2, 9), (3, 10), (4, None), (5, None), (6, None), (7, None)]
注:本文由純淨天空篩選整理自techni621大神的英文原創作品 Python – Itertools.zip_longest()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。