在Python中,高階函數(shù)是指接受其他函數(shù)作為參數(shù)或返回一個(gè)函數(shù)的函數(shù)。這里有一些關(guān)于如何使用高階函數(shù)的例子:
def apply(func, x):
return func(x)
def square(x):
return x * x
def cube(x):
return x * x * x
result = apply(square, 3) # 結(jié)果是9,因?yàn)閟quare(3) = 9
result = apply(cube, 3) # 結(jié)果是27,因?yàn)閏ube(3) = 27
def create_multiplier(factor):
def multiplier(x):
return x * factor
return multiplier
double = create_multiplier(2)
triple = create_multiplier(3)
result = double(5) # 結(jié)果是10,因?yàn)閐ouble(5) = 5 * 2 = 10
result = triple(5) # 結(jié)果是15,因?yàn)閠riple(5) = 5 * 3 = 15
這些例子展示了如何在Python中使用高階函數(shù)。希望這對(duì)您有所幫助!