#一、 records = [('f',1,2,4),('k',3,4,5),('z','e','d')] for key,value,*val in records: #可迭代對象,解構 if key == 'f': f(val) print('val:{0},{1}'.format(*val)) print('key:{0},value:{1}'.format(key,value))
#二、參數槽 #以*分隔,{非命名參數,命名參數} #不可以使用可變位置參數 #可變關鍵字參數必須在命名參數以後 def func(a,b,c=3,*,f=5,k=3,j,**kw): print(a) print(b) print(c) print(f) print(k) print(j) print(kw) func(9,4,f=4,j=7,s=8) 9 4 3 4 3 7 {'s': 8}
#三、遞歸 lst = [] #十進制轉換二進制 def to_binary(n): r = n % 2 if n >= 2: to_binary(n/2) lst.append(int(r)) to_binary(10) print(lst) [1, 0, 1, 0]
#四、生成器(斐波那契數列) def fib(): a,b = 0,1 while True: a,b = b,a+b# 解包,封包 yield b gen=fib() def func(x): for i in range(x): print(next(gen))
五、斐波那契數列: def fab(n): #(1) a = 1 b = 1 for i in range(n): print(a) a,b = b,a+b def fab(): #(2) a = 1 b = 1 while True: yield a a,b = b,a+b gen = fab() for i in range(10): print(next(gen)) def fab(n): #(3) if n == 1 or n == 0: return 1 return fab(n-1)+fab(n-2)