Python zip()函數用法執行個體分析,python執行個體分析

來源:互聯網
上載者:User

Python zip()函數用法執行個體分析,python執行個體分析

本文執行個體講述了Python zip()函數用法。分享給大家供大家參考,具體如下:

這裡介紹python中zip()函數的使用:

>>> help(zip)Help on built-in function zip in module __builtin__:zip(...)  zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

    Return a list of tuples, where each tuple contains the i-th element
    from each of the argument sequences.  The returned list is truncated
    in length to the length of the shortest argument sequence.

zip([seq1, ...])接受一系列可迭代對象作為參數,將對象中對應的元素打包成一個個元組,然後返回由這些元組組成的列表。若傳入參數的長度不等,則返回列表的長度和參數中長度最短的對象相同。

1》

>>> x=[1,2,3]>>> y=[1,2,3]>>> z=(1,2,3)>>> zip(x,y,z)[(1, 1, 1), (2, 2, 2), (3, 3, 3)]

2》

>>> x=(1,2,3,4)>>> y=[1,2,3]>>> zip(x,y) #傳入參數的長度不等,則返回列表的長度和參數中長度最短的對象相同[(1, 1), (2, 2), (3, 3)]

3》

>>> x(1, 2, 3, 4)>>> zip(x)[(1,), (2,), (3,), (4,)]

4》

>>> zip()[]

5》zip()配合*號操作符,可以將已經zip過的列表對象解壓

>>> x=[1,2,3]>>> y=['a','b','c']>>> z=[4,5,6]>>> xyz=zip(x,y,z)>>> xyz[(1, 'a', 4), (2, 'b', 5), (3, 'c', 6)]>>> zip(*xyz)[(1, 2, 3), ('a', 'b', 'c'), (4, 5, 6)]

6》

>>> x=[5,6,7]>>> [x] #[x]產生一個列表的列表,它只有一個元素x[[5, 6, 7]]>>> [x]*3 #[x] * 3產生一個列表的列表,它有3個元素,[x, x, x][[5, 6, 7], [5, 6, 7], [5, 6, 7]]>>> x[5, 6, 7]>>> zip(*[x]*3) #zip(* [x] * 3)等價於zip(x, x, x)[(5, 5, 5), (6, 6, 6), (7, 7, 7)]

7》

>>> name=['song','ping','python']>>> age=[26,26,27]>>> zip(name,age)[('song', 26), ('ping', 26), ('python', 27)]>>> for n,a in zip(name,age):...   print n,a...song 26ping 26python 27

聯繫我們

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