#!/usr/bin/python #coding=utf-8 #循環設計 #範圍函數 S = 'abcdefghijk' #a b c d e f g h i j k for i in range(0, len(S), 2):#0 1 2 3 4 5 6 7 8 9 10 11 print S[i] print len(S) #遍歷數組 S = 'abcdefghijk' for (index, char) in enumerate(S): print index print char #多個等長的序列 ta = [1, 2, 3] tb = [9, 8, 7] tc = ['a', 'b', 'c'] for (a, b, c) in zip(ta, tb, tc): print(a, b, c) #分解聚合 ta = [1,2,3] tb = [9,8,7] # cluster zipped = zip(ta,tb) print (zipped) # decompose na, nb = zip(*zipped) print(na, nb) #循環對象 f = open('test.txt') f.next() f.next() f.next() f.next() f.next() f.next() f.next() for line in open('test.txt'): print line #生成器 def gen(): a = 100 yield a a = a*8 yield a yield 1000 for i in gen(): print i def gen(): for i in range(4): yield i G = (x for x in range(4)) #表推導 L = [] for x in range(10): L.append(x**2) print L L = [x**2 for x in range(10)] print L #函數對象 #lambda函數 func = lambda x,y: x + y print func(3, 4) def func(x, y): return x + y print func(3, 4) #函數做爲參數傳遞 def test(f, a, b): print 'test' print f(a, b) test(func, 3, 5) def U(a, b, c): print 'U' print a(b, c) U(func, 5, 6) #map()函數,map()的功能是將函數對象依次做用於表的每個元素 re = map((lambda x:x+3),[1, 2, 3, 5, 6]) print re re = map((lambda x,y: x+y),[1,2,3],[6,7,9]) print re #filter()函數,若是函數對象返回的是True,則該次的元素被儲存於返回的表中 def func(a): if a > 100: return True else: return False print filter(func, [10, 56, 101, 500]) #reduce()函數,reduce能夠累進地將函數做用於各個參數 print reduce((lambda x, y: x + y), [1, 2, 3, 4,9]) #錯誤處理 re = iter(range(5)) try: for i in range(100): print re.next() except StopIteration: print 'here is end ',i print 'HaHaHaHa' ''' re = iter(range(5)) for i in range(100): print re.next() print 'HaHaHaHa' try: print(a*2) except TypeError: print("TypeError") except: print("Not Type Error & Error noted") def test_func(): try: m = 1/0 except NameError: print("Catch NameError in the sub-function") try: test_func() except ZeroDivisionError: print("Catch error in the main program") print 'Lalala' raise StopIteration('this is error') print 'Hahaha' ''' #動態類型 a = 3 a = 'au' print a a = 5 b = a a = a + 2 print a print b L1 = [1, 2, 3] L2 = L1 L1 = 1 print L1, L2 L1 =[1, 2, 3] L2 =L1 L1[0] = 10 print L2 #從動態類型看函數的參數傳遞 def f(x): x = 100 print x a = 1 f(a) print a def f(x): x[2] = 100 print x a =[1, 2, 3] f(a) print a xl =[1, 3, 5] yl =[9, 12, 13] L = [x**2 for (x,y) in zip(xl, yl) if y > 10] print L #經過參數傳遞,判斷數字、字符串、list、tuple、詞典等數據類型是否爲可變數據對象 a = 2 b = '啊哈' c = [1, 2, 3] d = (1, 2, 3) e = {'tom': 11, 'sam': 57, 'lily': 100} def num(x): #數字 x = 100 print x num(a) print a def str(x): #字符串 x = 'ade' print x str(b) print b def list(x): #list x[0] = 100 print x list(c) print c def tuple(x): #tuple x[0] = 100 print x tuple(d) raise StopIteration() print d def dic(x): #詞典 x['tom'] = 100 print x dic(e) print e