python中itertools模塊zip_longest函數實現邏輯
阿新 • • 發佈:2018-06-11
python itertools zip_longest 最近在看流暢的python,在看第14章節的itertools模塊,對其itertools中的相關函數實現的邏輯的實現
其中在zip_longest(it_obj1, ..., it_objN, fillvalue=None)時,其函數實現的功能和內置zip函數大致相同(實現一一對應),
不過內置的zip函數是已元素最少對象為基準,而zip_longest函數是已元素最多對象為基準,使用fillvalue的值來填充
以下是自己總結此函數的大致實現方法,和官方方法不同:
思路大致如此: 找出元素個數最多 ==>算出元素個數差值==>填充差值個元素到各個對象
def zip_longest(*it, **kwargs): its = {k: len(k) for k in it} # 這裏我是用字典把參數對象和參數的元素個數結果作為一個字典 max_num = max(its.values()) # 確定叠代對象元素最大值 result = [] # fillvalue = kwargs.get('fillvalue', None) # 元素較少的填充值 for x in range(max_num): # 已最大次為基準循環 result = [] for it in its: # 循環所有叠代對象,以便進行填充數據 element = list(it) # 將 if len(it) < max_num: # 如果叠代對象的元素個數比最大值小,則要填充數據 for i in range(max_num - len(it)): # 此為要填充數據的個數 element.append(fillvalue) # 填充操作,完成後所有的叠代對象的元素個數都為一致 result.append(element[x]) # 生成一一對應結果,存放到list中 yield tuple(result) # 將結果輸出
測試其結果:
res = zip_longest('abc', '12') for x in res: print(x)
結果為:
('a', '1') ('b', '2') ('c', None)
python中itertools模塊zip_longest函數實現邏輯