Python的zip函式
轉自:http://www.cnblogs.com/frydsh/archive/2012/07/10/2585370.html
zip函式接受任意多個(包括0個和1個)序列作為引數,返回一個tuple列表。具體意思不好用文字來表述,直接看示例:
1.示例1:
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
xyz = zip(x, y, z)
print xyz
執行的結果是:
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
從這個結果可以看出zip函式的基本運作方式。
2.示例2:
x = [1, 2, 3]
y = [4, 5, 6, 7]
xy = zip(x, y)
print xy
執行的結果是:
[(1, 4), (2, 5), (3, 6)]
從這個結果可以看出zip函式的長度處理方式。
3.示例3:
x = [1, 2, 3]
x = zip(x)
print x
執行的結果是:
[(1,), (2,), (3,)]
從這個結果可以看出zip函式在只有一個引數時運作的方式。
4.示例4:
x = zip()
print x
執行的結果是:
[]
從這個結果可以看出zip函式在沒有引數時運作的方式。
5.示例5:
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
xyz = zip(x, y, z)
u = zip(*xyz)
print u
執行的結果是:
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
一般認為這是一個unzip的過程,它的執行機制是這樣的:
在執行zip(*xyz)之前,xyz的值是:[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
那麼,zip(*xyz) 等價於 zip((1, 4, 7), (2, 5, 8), (3, 6, 9))
所以,執行結果是:[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
注:在函式呼叫中使用*list/tuple的方式表示將list/tuple分開,作為位置引數傳遞給對應函式(前提是對應函式支援不定個數的位置引數)
6.示例6:
x = [1, 2, 3]
r = zip(* [x] * 3)
print r
執行的結果是:
[(1, 1, 1), (2, 2, 2), (3, 3, 3)]
它的執行機制是這樣的:
[x]生成一個列表的列表,它只有一個元素x
[x] * 3生成一個列表的列表,它有3個元素,[x, x, x]
zip(* [x] * 3)的意思就明確了,zip(x, x, x)
相關文章
- python中zip()函式的用法Python函式
- python zip enumerate函式Python函式
- python中id()函式、zip()函式、map()函式、lamda函式Python函式
- Python學習之zip函式Python函式
- Python內部函式zip使用Python函式
- python基礎 函式之 強大的zipPython函式
- CoffeeScript攻略4.2:類似Python的zip函式Python函式
- 簡單介紹Python中的配對函式zip()Python函式
- 理解zip函式的工作流程函式
- spark三種清理資料的方式:UDF,自定義函式,spark.sql;Python中的zip()與*zip()函式詳解//及python中的*args和**kwargsSpark函式SQLPython
- python常用函式進階(2)之map,filter,reduce,zipPython函式Filter
- [PY3]——字典排序問題總結—(zip()函式、OrderedDict、itemgetter函式)排序函式
- 函式進階· 第3篇《常用內建函式filter()、map()、zip(),怎麼用的呢?》函式Filter
- Python hasattr() 函式 // python中hasattr()、getattr()、setattr()函式的使用Python函式
- Python的魔法函式Python函式
- python的常用函式Python函式
- python內建函式-eval()函式與exec()函式的區別Python函式
- Python strip函式和split函式Python函式
- Python 函式Python函式
- python函式Python函式
- Python 擴充之特殊函式(lambda 函式,map 函式,filter 函式,reduce 函式)Python函式Filter
- 『無為則無心』Python函式 — 25、Python中的函式Python函式
- Python函式與lambda 表示式(匿名函式)Python函式
- python(python中的super函式、)Python函式
- python入門必會的助手函式:dir()函式Python函式
- Python利用partial偏函式生成不同的聚合函式Python函式
- python的偏函式(partial)Python函式
- python函式的基本使用Python函式
- Python函式的進階Python函式
- Python自帶的函式Python函式
- Python 的函式註釋Python函式
- 【Python】常用的字串函式Python字串函式
- Python 函式進階-遞迴函式Python函式遞迴
- Python 函式進階-高階函式Python函式
- python函式每日一講 - int()函式Python函式
- python函式每日一講 - int()函式Python函式
- python函式每日一講 - eval函式Python函式
- Python私有函式和公開函式Python函式