在python中如何使用变量作为比较器?

2024-04-19 19:49:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些KPI,对一些人来说,超出目标值是好的,而对其他人来说是坏的。你知道吗

我能做点像这样的事吗

comparator = '<'
value = 100
target = 200

然后继续说

value comparator target

所以python将其视为100 < 200并返回True?你知道吗

对于上下文,我有一个KPI表,其格式如下:

KPI1: < 100 On Target, > 110 Action Required

KPI2: > 50 On Target, <

我计划通过它们和它们的相关数据来应用RAG评级。你知道吗


Tags: 数据truetargetvalueon格式requiredaction
2条回答

这可以工作(使用eval)

comparator_1  = '>'
x = 7
y = 12
print(eval('{} {} {}'.format(x,comparator_1,y)))
comparator_2  = '<'
print(eval('{} {} {}'.format(x,comparator_2,y)))

输出

False
True

你可以使用一流的方法。这允许您跳过导入operator模块,并且比使用eval()更安全:


def lt(a, b): return a < b
def gt(a, b): return a > b
def eq(a, b): return a == b

comparator = lt
print(comparator(4, 5))  # >>> True

相关问题 更多 >