Python 条件检查场景中评估的替代方案
我有这个json结构Python 条件检查场景中评估的替代方案,python,algorithm,Python,Algorithm,我有这个json结构 scenarios = [{"outcome_name":"outcome1", "checking_condition":[ { "db_key":"purchase_date", "operator":">" "db_value":"requested_d
scenarios = [{"outcome_name":"outcome1",
"checking_condition":[
{
"db_key":"purchase_date",
"operator":">"
"db_value":"requested_date"
},
{
"db_key":"purchase_amount",
"operator":"<"
"db_value":"5000"
}
]
outcome_selection_criteria:"index0 and index1"
}]
定义允许的运算符符号到实现它的函数的映射。然后,当您从条件中读取运算符时,只需查找所需的函数 通常,由
运算符导出的函数比自己使用def
或lambda
表达式定义等效函数更有效
import operators
ops = {
"<": operator.lt, # lambda x, y: x < y
">": operator.gt, # lambda x, y: x > y
# ...
}
for outcome in scenarios:
for cond in outcome["checking_condition"]:
op = cond["operator"]
# Whatever foo is, for however you get the actual values to compare
lhs = foo(cond["db_key"])
rhs = foo(cond["db_value"])
result = ops[op](lhs, rhs)
...
导入操作符
ops={
“”:operator.gt,#lambda x,y:x>y
# ...
}
对于场景中的结果:
对于结果中的条件[“检查条件”]:
op=cond[“运算符”]
#不管foo是什么,但是您可以得到实际值进行比较
lhs=foo(cond[“db_key”])
rhs=foo(cond[“db_值”])
结果=操作[op](左、右)
...
那么您将购买日期
作为变量?向我们展示你丑陋的/缓慢的/不安全的评估代码我在redis中保存了一个主变量,其中有一个键是purchase date。相关:添加了实际代码的一部分,希望这可以解释,所以我在每个文件中都有多个场景,我正在迭代它们,我的代码一个接一个地迭代遍历一个文件,直到它到达层次结构中的某个点,而此时它没有前进的方向@让·弗朗索瓦oisFabre@Jean-弗朗索瓦·法布:谢谢你的另一个评估答案。。哇,我不知道我们能做到。
import operators
ops = {
"<": operator.lt, # lambda x, y: x < y
">": operator.gt, # lambda x, y: x > y
# ...
}
for outcome in scenarios:
for cond in outcome["checking_condition"]:
op = cond["operator"]
# Whatever foo is, for however you get the actual values to compare
lhs = foo(cond["db_key"])
rhs = foo(cond["db_value"])
result = ops[op](lhs, rhs)
...