Python zip函數

來源:互聯網
上載者:User

標籤:

This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence. When there are multiple arguments which are all of the same length, zip() is similar to map() with an initial argument of None. With a single sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list.

The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n).

zip() in conjunction with the * operator can be used to unzip a list:

 

pythonAPI上面說的

下面自己上例子:

 

x=[1,2,3]y=[4,5,6]z=[7,8,9]print zip(x)print zip(x,y)print zip(x,y,z)

結果是:

[(1,), (2,), (3,)][(1, 4), (2, 5), (3, 6)][(1, 4, 7), (2, 5, 8), (3, 6, 9)]

 

可以看出zip是把同一維度資料放在一個list中

 

 

 

w= zip(x,y,z)for a,b,c in w:    print ‘a:{0},b:{1},c:{2}‘.format(a,b,c)

結果是:

a:1,b:4,c:7a:2,b:5,c:8a:3,b:6,c:9

for是把list中的tuple中的每個元素輸出

 

print type(w), type(w[1])

 

<type ‘list‘> <type ‘tuple‘>

 

 

x=[1,2,3]y=[4,5,6]z=[7,8,9]w= zip(x,y,z)print wprint zip(*w)

 

結果:

[(1, 4, 7), (2, 5, 8), (3, 6, 9)][(1, 2, 3), (4, 5, 6), (7, 8, 9)]

 

這是zip(*w)是把功能返回去而已

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.