您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關(guān)如何在Python中使用zip()函數(shù),小編覺(jué)得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說(shuō),跟著小編一起來(lái)看看吧。
python中zip()函數(shù)的使用:
>>> 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, ...])
接受一系列可迭代對(duì)象作為參數(shù),將對(duì)象中對(duì)應(yīng)的元素打包成一個(gè)個(gè)元組,然后返回由這些元組組成的列表。若傳入?yún)?shù)的長(zhǎng)度不等,則返回列表的長(zhǎng)度和參數(shù)中長(zhǎng)度最短的對(duì)象相同。
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) #傳入?yún)?shù)的長(zhǎng)度不等,則返回列表的長(zhǎng)度和參數(shù)中長(zhǎng)度最短的對(duì)象相同 [(1, 1), (2, 2), (3, 3)]
3》
>>> x (1, 2, 3, 4) >>> zip(x) [(1,), (2,), (3,), (4,)]
4》
>>> zip() []
5》zip()配合*號(hào)操作符,可以將已經(jīng)zip過(guò)的列表對(duì)象解壓
>>> 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]生成一個(gè)列表的列表,它只有一個(gè)元素x [[5, 6, 7]] >>> [x]*3 #[x] * 3生成一個(gè)列表的列表,它有3個(gè)元素,[x, x, x] [[5, 6, 7], [5, 6, 7], [5, 6, 7]] >>> x [5, 6, 7] >>> zip(*[x]*3) #zip(* [x] * 3)等價(jià)于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 26 ping 26 python 27
以上就是如何在Python中使用zip()函數(shù),小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見(jiàn)到或用到的。希望你能通過(guò)這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。