Python:zip()函數

來源:互聯網
上載者:User

標籤:多個參數   元素   定義   pytho   iterable   col   類型   函數   color   

zip()函數的定義

  • 從參數中的多個迭代器取元素組合成一個新的迭代器;
  • 返回:返回一個zip對象,其內部元素為元組;可以轉化為列表或元組;
  • 傳入參數:元組、列表、字典等迭代器。

zip()函數的用法

當zip()函數中只有一個參數時

zip(iterable)從iterable中依次取一個元祖,組成一個元祖

# zip()函數單個參數list1 = [1, 2, 3, 4]tuple1 = zip(list1)# 列印zip函數的傳回型別print("zip()函數的傳回型別:\n", type(tuple1))# 將zip對象轉化為列表print("zip對象轉化為列表:\n", list(tuple1))#輸出結果zip()函數的傳回型別:<class ‘zip‘>zip對象轉化為列表:[(1,), (2,), (3,), (4,)]

當zip()函數裡有多個參數時:

# practice arealist_1 = [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘, ‘h‘]list_2 = [ 9 ,  8 ,  7 ,  6 ,  5 ,  4 ,  3 ,  2 ]for i in range(len(list_1)):    if list_2[i] % 2 == 1:        print(list_1[i],end=‘ ‘) print("")#在這裡要用zip把兩個列表打包成包含兩個元祖的一個列表for i,j in zip(list_1,list_2):    if j % 2 ==0:        print(i,end=‘ ‘)        a c e g b d f h 

 

Python:zip()函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.