gpt4 book ai didi

python - 如何定义具有条件作为输入的函数?

转载 作者:行者123 更新时间:2023-12-05 01:23:00 24 4
gpt4 key购买 nike

我需要一个将规则/条件作为输入的函数。例如,给定一个整数数组,检测所有大于 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))

我应该如何编写这样的函数?

最佳答案

函数是一流的对象,这意味着您可以将它们视为任何其他变量。

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)

在您的示例中,您要使用的条件可以表示为一个简单的表达式。 python lambda 关键字允许您将表达式定义为其他语句和表达式中的匿名函数。因此,您可以替换函数的显式 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)

关于python - 如何定义具有条件作为输入的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73005057/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com