Python3_函式:高價函式
一、程式設計的3種方法:
- 面向過程:將一個大問題分成若干個小問題進行逐一的處理
- 函數語言程式設計:是將程式語言的函式和數學意義的函式相結合,如y=2*x+1相當於
def func(x): return 2 * x + 1
- 面向物件:將事物的本質通過建立一系列模型來體現出事物的本質和特徵
二、高階函式:
1、高階函式的定義:
- 函式接收的引數可以是另一個函式的函式名
- 在函式的返回值中包含於一個函式名
2、3個常用的內建高階函式:
2.1:map()函式:
- 將列表[1, 2, 3, 4]中的每個元素進行加10
方法1:
list01 = [1, 2, 3, 4] def func(x): return x + 10 def add_num(function, array): res = [] for i in array: res.append(function(i)) return res print(add_num(func, list01))
方法2:
list01 = [1, 2, 3, 4] def add_num(function, array): res = [] for i in array: res.append(function(i)) return res print(add_num(lambda x:x+10, list01))
使用map()函式:
list01 = [1, 2, 3, 4] print(list(map(lambda x:x+10, list01)))
執行結果:
[11, 12, 13, 14]
map()函式的用法:
map(處理方法, 可迭代物件)
功能:
對可迭代物件中的每個元素按照指定的處理方法進行操作,最後以迭代型別輸出,可將其轉換為相應的資料型別進行輸出
2.2:filter()函式:
- 將列表[{"class":101, "name":"zhang"},{"class":102, "name":"li"},{"class":201, "name":"wang"},{"class":202, "name":"zhao"}]中的年級是一年級的刪除
方法1:
def func(x): return x["class"][0] def class_list(function, array): new_list = [] for i in array: if function(i) != "1": new_list.append(i) return new_list print(class_list(func, student_list))
方法2:
def class_list(function, array): new_list = [] for i in array: if function(i) != "1": new_list.append(i) return new_list print(class_list(lambda x:x["class"][0], student_list))
filter()方法:
print(list(filter(lambda x:x["class"][0] != "1", student_list)))
執行結果:
[{'class': '201', 'name': 'wang'}, {'class': '202', 'name': 'zhao'}]
filter()函式的用法:
filter(處理方法, 可迭代物件)
“處理方法”得到的結果必須是一個布林值
功能:
將可迭代物件中的元素按照指定的處理方法進行刪選後以迭代型別輸出,可將其轉換為相應的資料型別進行輸出
2.3:reduce()函式:
在Python2中可直接使用reduce()函式,在Python3中需要匯入functools模組後才能使用。
- 將列表[2, 3, 4, 10]中的元素跟指定的初始值(可選)累乘後進行輸出
方法1:
情況1:沒有指定初始值
def func(x, y): return x * y def times(function, array, init=None): if init == None: res = 1 else: res = init for num in array: res = function(res, num) # res *= num return res print(times(func, list01))
情況2:指定初始值
def func(x, y): return x * y def times(function, array, init=None): if init == None: res = 1 else: res = init for num in array: res = function(res, num) # res *= num return res print(times(func, list01, 100))
方法2:
情況1:沒有指定初始值
def times(function, array, init=None): if init == None: res = 1 else: res = init for num in array: res = function(res, num) # res *= num return res print(times(lambda x,y:x*y, list01))
情況2:指定初始值
def times(function, array, init=None): if init == None: res = 1 else: res = init for num in array: res = function(res, num) # res *= num return res print(times(lambda x,y:x*y, list01, 100))
reduce()方法:
情況1:沒有指定初始值
from functools import reduce print(reduce(lambda x,y:x*y, list01))
情況2:指定初始值
from functools import reduce print(reduce(lambda x,y:x*y, list01, 100))
reduce()函式用法:
reduce(處理方法, 可迭代物件, 初始值)
功能:
將可迭代物件中的元素按照制定的處理方法進行運算後輸出