我需要一个将规则/条件作为输入的函数。例如,给定一个整数数组,检测所有大于 2 的数字,以及所有大于 4 的数字。我知道这可以在没有函数的情况下轻松实现,但我需要将其放在函数内部。我想要的功能就像
def _select(x,rule):
outp = rule(x)
return outp
L = np.round(np.random.normal(2,4,50),decimals=2)
y = _select(x=L,rule=(>2))
y1 = _select(x=L,rule=(>4))
Run Code Online (Sandbox Code Playgroud)
我应该如何编写这样的函数?
函数是第一类对象,这意味着您可以将它们视为任何其他变量。
import numpy as np
def _select(x,rule):
outp = rule(x)
return outp
def rule_2(val):
return val > 2
def rule_4(val):
return val > 4
L = np.round(np.random.normal(2,4,50),decimals=2)
y = _select(x=L,rule=rule_2)
print(y)
y1 = _select(x=L,rule=rule_4)
print(y1)
Run Code Online (Sandbox Code Playgroud)
在您的示例中,您要使用的条件可以表示为简单的表达式。pythonlambda关键字允许您将表达式定义为其他语句和表达式中的匿名函数。所以,你可以替换def函数的显式
import numpy as np
def _select(x,rule):
outp = rule(x)
return outp
L = np.round(np.random.normal(2,4,50),decimals=2)
y = _select(x=L,rule=lambda val: val > 2)
print(y)
y1 = _select(x=L,rule=lambda val: val > 4)
print(y1)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
453 次 |
| 最近记录: |