For 迴圈語句 基礎知識 for迴圈可以遍歷任何序列的項目,如一個列表或者一個字元串。 語法: for 迴圈規則: do sth 判斷對象是否可迭代 zip() 函數 函數用於將可迭代的對象作為參數,將對象中對應的元素打包成一個個元組,然後返回由這些元組組成的列表。 如果各個迭代器的元素個數不一致 ...
For 迴圈語句
基礎知識
for迴圈可以遍歷任何序列的項目,如一個列表或者一個字元串。
語法:
for 迴圈規則:
do sth
1 >>> for i in "python" : #用i這個變數遍歷這個字元串的每一個字元 2 ... print i #將遍歷的字元列印出來 3 ... 4 p 5 y 6 t 7 h 8 o 9 n 10 >>> lst =["baidu","google","ali"] 11 >>> for i in lst: #用變數i遍歷這個列表,將每個元素列印出來 12 ... print i 13 ... 14 baidu 15 google 16 ali 17 >>> t =tuple(lst) 18 >>> t 19 ('baidu', 'google', 'ali') 20 >>> for i in t: #用變數i遍歷元組,將每個元素列印出來 21 ... print i 22 ... 23 baidu 24 google 25 ali 26 >>> d =dict([("lang","python"),("website","baidu"),("city","beijing")]) 27 >>> d 28 {'lang': 'python', 'website': 'baidu', 'city': 'beijing'} 29 >>> for k in d: #用變數k遍歷這個字典,將每個key列印出來 30 ... print k 31 ... 32 lang 33 website 34 city 35 >>> for k in d: #用變數k遍歷字典d 36 ... print k,"-->",d[k] #將key值和value值列印出來 37 ... 38 lang --> python 39 website --> baidu 40 city --> beijing 41 >>> d.items() #以列表返回可遍歷的(鍵, 值) 元組 42 [('lang', 'python'), ('website', 'baidu'), ('city', 'beijing')] 43 >>> for k,v in d.items(): #用key value遍歷d.items()的元組列表 44 ... print k,"-->",v #取得key ,value 45 ... 46 lang --> python 47 website --> baidu 48 city --> beijing 49 >>> for k,v in d.iteritems(): iteritems 返回的是迭代器 推薦使用這個 50 ... print k,v 51 ... 52 lang python 53 website baidu 54 city beijing 55 >>> d.itervalues() 返回的是迭代器 56 <dictionary-valueiterator object at 0x0000000002C17EA8> 57 >>>
判斷對象是否可迭代
1 >>> import collections #引入標準庫 2 >>> isinstance(321,collections.Iterable) #返回false,不可迭代 3 False 4 >>> isinstance([1,2.3],collections.Iterable) #返回true,可迭代 5 True
1 >>> l =[1,2,3,4,5,6,7,8,9] 2 >>> l[4:] 3 [5, 6, 7, 8, 9] 4 >>> for i in l[4:]: #遍歷4以後的元素 5 ... print i 6 ... 7 5 8 6 9 7 10 8 11 9 12 >>> help(range) #函數可創建一個整數列表,一般用在 for 迴圈中 13 Help on built-in function range in module __builtin__: 14 15 range(...) 16 range(stop) -> list of integers 17 range(start, stop[, step]) -> list of integers #計數從 start 開始,計數到 stop 結束,但不包括 stop,step:步長,預設為1 18 19 Return a list containing an arithmetic progression of integers. 20 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. 21 When step is given, it specifies the increment (or decrement). 22 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! 23 These are exactly the valid indices for a list of 4 elements. 24 25 >>> range(9) 26 [0, 1, 2, 3, 4, 5, 6, 7, 8] 27 >>> range(2,8) 28 [2, 3, 4, 5, 6, 7] 29 >>> range(1,9,3) 30 [1, 4, 7] 31 >>> l 32 [1, 2, 3, 4, 5, 6, 7, 8, 9] 33 >>> range(0,9,2) 34 [0, 2, 4, 6, 8] 35 >>> for i in range(0,9,2): 36 ... print i 37 ... 38 0 39 2 40 4 41 6 42 8 43 >>>
1 #! /usr/bin/env python 2 #coding:utf-8 3 4 aliquot =[] #創建一個空的列表 5 6 for n in range(1,100): #遍歷1到100 的整數 7 if n %3==0: #如果被3整除 8 aliquot.append(n) #將n值添加到列表中 9 10 print aliquot
zip() 函數
函數用於將可迭代的對象作為參數,將對象中對應的元素打包成一個個元組,然後返回由這些元組組成的列表。
如果各個迭代器的元素個數不一致,則返回列表長度與最短的對象相同,利用 * 號操作符,可以將元組解壓為列表。
返回一個列表,這列表是以元組為元素
1 >>> a =[1,2,3,4,5] 2 >>> b =[9,8,7,6,5] 3 >>> c =[] 4 >>> for i in range(len(a)): 5 ... c.append(a[i]+b[i]) 6 >>> for i in range(len(a)): 7 ... c.append(a[i]+b[i]) 8 ... 9 >>> c 10 [10, 10, 10, 10, 10] 11 >>> help(zip) 12 Help on built-in function zip in module __builtin__: 13 14 zip(...) 15 zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)] 16 17 Return a list of tuples, where each tuple contains the i-th element 18 from each of the argument sequences. The returned list is truncated 19 in length to the length of the shortest argument sequence. 20 21 >>> a 22 [1, 2, 3, 4, 5] 23 >>> b 24 [9, 8, 7, 6, 5] 25 >>> zip(a,b) 26 [(1, 9), (2, 8), (3, 7), (4, 6), (5, 5)] 27 >>> c =[1,2,3] 28 >>> zip(c,b) 29 [(1, 9), (2, 8), (3, 7)] 30 >>> zip(a,b,c) 31 [(1, 9, 1), (2, 8, 2), (3, 7, 3)] 32 >>> d=[] 33 >>> for x,y in zip(a,b): 34 ... d.append(x+y) 35 ... 36 >>> d 37 [10, 10, 10, 10, 10] 38 >>> r =[(1,2),(3,4),(5,6),(7,8)] 39 >>> zip(*r) 40 [(1, 3, 5, 7), (2, 4, 6, 8)] 41 >>>
enumerate()函數
函數用於將一個可遍歷的數據對象(如列表、元組或字元串)組合為一個索引序列,同時列出數據和數據下標,一般用在 for 迴圈當中。
語法:
enumerate(sequence, [start=0])
sequence -- 一個序列、迭代器或其他支持迭代對象
start -- 下標起始位置。
返回值: enumerate枚舉對象
1 >>> help(enumerate) 2 Help on class enumerate in module __builtin__: 3 4 class enumerate(object) 5 | enumerate(iterable[, start]) -> iterator for index, value of iterable 6 | 7 | Return an enumerate object. iterable must be another object that supports 8 | iteration. The enumerate object yields pairs containing a count (from 9 | start, which defaults to zero) and a value yielded by the iterable argument. 10 | enumerate is useful for obtaining an indexed list: 11 | (0, seq[0]), (1, seq[1]), (2, seq[2]), ... 12 | 13 | Methods defined here: 14 | 15 | __getattribute__(...) 16 | x.__getattribute__('name') <==> x.name 17 | 18 | __iter__(...) 19 | x.__iter__() <==> iter(x) 20 | 21 | next(...) 22 | x.next() -> the next value, or raise StopIteration 23 | 24 | ---------------------------------------------------------------------- 25 | Data and other attributes defined here: 26 | 27 | __new__ = <built-in method __new__ of type object> 28 | T.__new__(S, ...) -> a new object with type S, a subtype of T 29 30 >>> weeks =["sun","mon","tue","web","tue","fri","sta"] 31 >>> for i,day in enumerate(weeks): 32 ... print str(i)+":"+day 33 ... 34 0:sun 35 1:mon 36 2:tue 37 3:web 38 4:tue 39 5:fri 40 6:sta 41 >>> for i in range(len(weeks)): 42 ... print str(i)+":"+weeks[i] 43 ... 44 0:sun 45 1:mon 46 2:tue 47 3:web 48 4:tue 49 5:fri 50 6:sta 51 >>> raw ="Do you love canglaoshi? canglaoshi is a good teacher." 52 >>> raw_lst =raw.split(" ") 53 >>> raw_lst 54 ['Do', 'you', 'love', 'canglaoshi?', 'canglaoshi', 'is', 'a', 'good', 'teacher.'] 55 >>> for i,w in enumerate(raw_lst): 56 ... if w =="canglaoshi": 57 ... raw_lst[i]="luolaoshi" 58 ... 59 >>> raw_lst 60 ['Do', 'you', 'love', 'canglaoshi?', 'luolaoshi', 'is', 'a', 'good', 'teacher.'] 61 >>> for i,w in enumerate(raw_lst): 62 ... if "canglaoshi" in w: 63 ... raw_lst[i]="luolaoshi" 64 ... 65 >>> raw_lst 66 ['Do', 'you', 'love', 'luolaoshi', 'luolaoshi', 'is', 'a', 'good', 'teacher.'] 67 >>> a =range(10) 68 >>> a 69 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 70 >>> s =[] 71 >>> for i in a: 72 ... s.append(i*i) 73 ... 74 >>> s 75 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 76 >>> b = [i*i for i in a] #列表解析 77 >>> b 78 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 79 >>> c = [i*i for i in a if i%3==0] #列表解析,加入限制條件 80 >>> c 81 [0, 9, 36, 81] 82 >>>
列表解析