# 高階函數# 數學概念 y = g(f(x))# 高階函數必須知足至少一個條件# 1 接受一個或多個函數做爲參數(如:f(x))# 2 返回一個函數對象def counter(base): def inner(step = 1): # 當成本地變量來理解 nonlocal base base = base + step return base return innerfoo1 = counter(10)foo2 = counter(10)print(foo1 == foo2) # false# 自定義sort函數# 1lst = [1, 2, 5, 4, 2, 3, 5, 6]def sort(iterable): ret = [] for x in iterable: for i, y in enumerate(ret): # 函數用於將一個可遍歷的數據對象組合爲一個索引序列,同時列出數據和數據下標,通常用在 for 循環當中。 if x > y: ret.insert(i, x) break else: ret.append(x) return retprint(sort(lst))# 2lst = [1, 2, 5, 4, 2, 3, 5, 6]def sort(iterable, reverse=False): ret = [] for x in iterable: for i, y in enumerate(ret): flag = x>y if reverse else x<y if flag: ret.insert(i, x) break else: ret.append(x) return retprint(sort(lst))# 3lst = [1, 2, 5, 4, 2, 3, 5, 6]def comp(a, b): return a < bdef sort(iterable, key=comp, reverse=True): ret = [] for x in iterable: for i, y in enumerate(ret): flag = key(x, y) if reverse else key(y, x) if flag: ret.insert(i, x) break else: ret.append(x) return retprint(sort(lst))# 4lst = [1, 2, 5, 4, 2, 3, 5, 6]def sort(iterable, key=lambda a,b:a<b, reverse=False): ret = [] for x in iterable: for i, y in enumerate(ret): flag = key(x, y) if reverse else key(y, x) if flag: ret.insert(i, x) break else: ret.append(x) return retprint(sort(lst))# 5 最終的高階函數lst = [1, 2, 5, 4, 2, 3, 5, 6]def sort(iterable, key=lambda a,b:a<b): ret = [] for x in iterable: for i, y in enumerate(ret): if key(x, y): ret.insert(i, x) break else: ret.append(x) return retprint(sort(lst))print(sort(lst, lambda a,b:a>b))# 6lst = [1, 2, 5, 4, 2, 3, 5, 6]def sort(iterable, key=None): ret = [] if key is None: key = lambda a,b:a<b for x in iterable: for i, y in enumerate(ret): if key(x, y): ret.insert(i, x) break else: ret.append(x) return retprint(sort(lst))print(sort(lst, lambda a,b:a>b))# 內建函數-高階函數# sorted(iterable[, key][, reverse]) --> 值不變# 對一個可迭代對象的全部元素排序,返回一個新的列表,排序規則爲key定義的函數,reverse表示是否反轉# sorted(lst, key=lambda x:6-x) 返回新列表lst = [1, 2, 5, 4, 2, 3, 5, 6, 7]print(sorted(lst, key=lambda x:6-x)) # key函數只是用來比較,不影響排序# list.sort(key=lambda x:6-x) 就地修改lst = [1, 2, 5, 4, 2, 3, 5, 6, 7]print(lst.sort(key=lambda x:6-x))# filter(function, iterable) --> 留下要的值 filter object# 過濾可迭代對象的元素,返回一個迭代器# function一個具備一個參數的函數,返回bool# 例:過濾出數列中能被3整除的數字print(list(filter(lambda x:x%3==0, [1, 9, 55, -3, 78, 28, 123])))# map(function, *iterables) --> 返回新的值 map object# 對多個可迭代對象的元素按照指定的函數進行映射,返回一個迭代器# list(map(lambda x:2*x+1, range(5)))print(list(map(lambda x:2*x+1, range(5))))# dict(map(lambda x:(x%5, x), range(500)))print(dict(map(lambda x:(x%5, x), range(500)))) {0: 495, 1: 496, 2: 497, 3: 498, 4: 499}