python for 迴圈
for的基本操作
for是用來迴圈的,是從某個物件那裡依次將元素讀取出來。
>>> name_str = "hiekay" >>> for i in name_str: #可以對str使用for迴圈 ... print i, ... h i e k a y >>> name_list = list(name_str) >>> name_list ['h', 'i', 'e', 'k', 'a', 'y'] >>> for i in name_list: #對list也能用 ... print i, ... h i e k a y >>> name_set = set(name_str) #set還可以用 >>> name_set set(['a', 'e', 'i', 'h', 'k', 'y']) >>> for i in name_set: ... print i, ... h i e k a y >>> name_tuple = tuple(name_str) >>> name_tuple ('h', 'i', 'e', 'k', 'a', 'y') >>> for i in name_tuple: #tuple也能呀 ... print i, ... h i e k a y >>> name_dict={"name":"hiekay","lang":"python","website":"hiekay.github.io"} >>> for i in name_dict: #dict也不例外 ... print i,"-->",name_dict[i] ... lang --> python website --> hiekay.github.io name --> hiekay
for在list解析中,用途也不可小覷,這在講解list解析的時候,也已說明,不過,還是再複習一下為好,所謂學而時常複習之,不亦哈哈乎。
>>> one = range(1,9)
>>> one
[1, 2, 3, 4, 5, 6, 7, 8]
>>> [ x for x in one if x%2==0 ]
[2, 4, 6, 8]
將上面所說的for迴圈,概括一下,就是下圖所示:
用一個文字表述:
for iterating_var in sequence: statements
iterating_var是物件sequence的迭代變數,也就是sequence必須是一個能夠有某種序列的物件,特別注意沒某種序列,就是說能夠按照一定的腳標獲取元素。當然,檔案物件屬於序列,我們沒有用腳標去獲取每行,如果把它讀取出來,因為也是一個str,所以依然可以用腳標讀取其內容。
##zip
zip是什麼東西?在互動模式下用help(zip),得到官方文件是:
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.
通過實驗來理解上面的文件:
>>> a = "hiekay"
>>> b = "github"
>>> zip(a,b)
[('h', 'g'), ('i', 'i'), ('e', 't'), ('k', 'h'), ('a', 'u'), ('y', 'b')]
>>> c = [1,2,3]
>>> d = [9,8,7,6]
>>> zip(c,d)
[(1, 9), (2, 8), (3, 7)]
>>> e = (1,2,3)
>>> f = (9,8)
>>> zip(e,f)
[(1, 9), (2, 8)]
>>> m = {"name","lang"}
>>> n = {"hiekay","python"}
>>> zip(m,n)
[('lang', 'python'), ('name', 'hiekay')]
>>> s = {"name":"hiekay"}
>>> t = {"lang":"python"}
>>> zip(s,t)
[('name', 'lang')]
zip是一個內建函式,它的引數必須是某種序列資料型別,如果是字典,那麼鍵視為序列。然後將序列對應的元素依次組成元組,做為一個list的元素。
下面是比較特殊的情況,引數是一個序列資料的時候,生成的結果樣子:
>>> a
'hiekay'
>>> c
[1, 2, 3]
>>> zip(c)
[(1,), (2,), (3,)]
>>> zip(a)
[('q',), ('i',), ('w',), ('s',), ('i',), ('r',)]
這個函式和for連用,就是實現了:
>>> c
[1, 2, 3]
>>> d
[9, 8, 7, 6]
>>> for x,y in zip(c,d): #實現一對一對地列印
... print x,y
...
1 9
2 8
3 7
>>> for x,y in zip(c,d): #把兩個list中的對應量上下相加。
... print x+y
...
10
10
10
上面這個相加的功能,如果不用zip,還可以這麼寫:
>>> length = len(c) if len(c)<len(d) else len(d) #判斷c,d的長度,將短的長度拿出來
>>> for i in range(length):
... print c[i]+d[i]
...
10
10
10
以上兩種寫法那個更好呢?還可以這麼做呢:
>>> [ x+y for x,y in zip(c,d) ]
[10, 10, 10]
前面多次說了,list解析強悍呀。當然,還可以這樣的:
>>> [ c[i]+d[i] for i in range(length) ]
[10, 10, 10]