##python 有一種遺留的現象: 狀況1:參數遺留問題python
def add_end(L=[]): L.append('end') return L a = [1,2,3] print (add_end(a)) print (add_end()) print (add_end()) print (add_end()) 結果 [1, 2, 3, 'end'] ['end'] ['end', 'end'] ['end', 'end', 'end']
def add_end(L=None): if L == None: L=[] L.append('end') return L a = [1,2,3,4] print(add_end(a)) print(add_end()) print(add_end()) 結果 [1, 2, 3, 4, 'end'] ['end'] ['end']
狀況二:閉包問題閉包
def count(): fs = [] for i in range(1, 4): def f(): return i*i fs.append(f) return fs f1, f2, f3 = count() 結果 >>> f1() 9 >>> f2() 9 >>> f3() 9
def count(): def f(j): def g(): return j*j return g fs = [] for i in range(1, 4): fs.append(f(i)) # f(i)馬上被執行,所以i的當前值被傳入f() return fs 結果: >>> f1, f2, f3 = count() >>> f1() 1 >>> f2() 4 >>> f3() 9
** 狀況一引用自廖老師的教程app
** 狀況二引用自廖老師的教程函數
codewar題目:在混有字母數字的列表中找出數字並創建列表,個人拙解。3d
def filter_list(l): 'return a new list with the strings filtered out' L=[] #if L!=None: # L=[] for num in l: if isinstance(num, int): L.append(num) return L
def filter_list(l): 'return a new list with the strings filtered out' return [i for i in l if isinstance(i, int)]