python中itertools模組zip_longest函數實現邏輯

來源:互聯網
上載者:User

標籤: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函數實現邏輯

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.