簡體   English   中英

將多個函數分配給單個變量?

[英]Assign multiple functions to a single variable?

在Python中,我們可以為變量賦值。 例如,math.sine函數:

sin = math.sin
rad = math.radians
print sin(rad(my_number_in_degrees))

有沒有簡單的方法為變量分配多個函數(即函數的函數)? 例如:

sin = math.sin(math.radians) # I cannot use this with brackets
print sin (my_number_in_degrees)

只需創建一個包裝函數:

def sin_rad(degrees):
    return math.sin(math.radians(degrees))

正常調用您的包裝函數:

print sin_rad(my_number_in_degrees)

我認為作者想要的是某種形式的功能鏈。 一般來說,這很難,但對於那些功能來說可能是可能的

  1. 采取一個論點,
  2. 返回單個值,
  3. 列表中前一個函數的返回值與下一個函數的輸入類型的返回值是列表相同

讓我們說有一個我們需要鏈接的函數列表,從中獲取一個參數,並返回一個參數。 此外,類型是一致的。 像這樣......

functions = [np.sin, np.cos, np.abs]

是否有可能編寫一個所有這些鏈接在一起的通用函數? 好吧,我們可以使用reduce雖然,Guido並不特別喜歡mapreduce實現並且即將把它們拿出來......

像這樣......

>>> reduce(lambda m, n: n(m), functions, 3)
0.99005908575986534

現在我們如何創建一個這樣做的功能? 好吧,只需創建一個獲取值並返回函數的函數:

import numpy as np 

def chainFunctions(functions):
    def innerFunction(y):
        return reduce(lambda m, n: n(m), functions, y)
    return innerFunction

if __name__ == '__main__':
    functions = [np.sin, np.cos, np.abs]
    ch = chainFunctions( functions )
    print ch(3)

您可以編寫輔助函數來為您執行函數組合 ,並使用它來創建所需的變量類型。 一些不錯的功能是它可以將可變數量的函數組合在一起,每個函數都接受可變數量的參數。

import math
try:
    reduce
except NameError:  # Python 3
    from functools import reduce

def compose(*funcs):
    """ Compose a group of functions (f(g(h(...)))) into a single composite func. """
    return reduce(lambda f, g: lambda *args, **kwargs: f(g(*args, **kwargs)), funcs)

sindeg = compose(math.sin, math.radians)

print(sindeg(90))  # -> 1.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM