我正在用 Python 实现一个规则评分系统。每个元素以 100 分开始,并根据一组规则进行扣除。
有没有一种更简洁的方法可以通过在 Python 中使用某种类型的规则库来完成此操作?
def get_score(element):
score = 100
if rule_1_match(element):
score -= 50
if rule_2_match(element):
score -= 20
if rule_3_match(element):
score -= 25
if rule_4_match(element):
score -= 10
# Min score is 0 so we take the max of 0 and the score
return max(score, 0)
答案 0 :(得分:1)
您可以将规则及其分数排列为元组列表:
rules = [(rule_1_match, 50), (rule_2_match, 20), ...]
然后迭代规则列表并扣除匹配分数:
def get_score(element):
score = 100
for rule, deduct_score in rules:
if rule(element):
score -= deduct_score
# Min score is 0 so we take the max of 0 and the score
return max(score, 0)