如何编写适配不同键长度的Python字典推导式计算关系权重
解决方案
要让代码支持任意长度的关联键组合,只需修改relationship_scores字典推导式中的乘积计算逻辑和条件判断逻辑,具体改动如下:
关键调整点
- 替换固定索引的乘积计算:不再硬写
relationship[0]和relationship[1],改用math.prod()计算任意数量组件分数的乘积(Python 3.8+支持,低版本可改用functools.reduce) - 替换固定数量的条件判断:不再只校验前两个组件的值,改用
all()检查关联组合内所有组件是否都为True
修改后的完整代码
import math component_weights = { 'quality': 0.3, 'price': 0.2, 'customer_service': 0.2, 'features': 0.3, } # 定义关联权重乘数 relationship_multipliers = { ('quality', 'customer_service','features'): 1.6, ('quality', 'customer_service'): 1.5, ('customer_service', 'features'): 1.5, } # 组件状态值 component_values = { 'quality': True, 'price': False, 'customer_service': True, 'features': True, } component_scores = { name: value * component_weights[name] for name, value in component_values.items() } print(component_scores) # 适配任意长度关联组合的关系分数计算 relationship_scores = { relationship: ( math.prod(component_scores[comp] for comp in relationship) * relationship_multipliers[relationship] ) for relationship in relationship_multipliers.keys() if all(component_values[comp] for comp in relationship) } print(relationship_scores) weighted_score = sum(component_scores.values()) + sum(relationship_scores.values()) print(weighted_score)
低Python版本兼容方案
若Python版本低于3.8(无math.prod()),可改用functools.reduce实现乘积计算:
from functools import reduce import operator # 替换原代码中的math.prod部分 reduce(operator.mul, (component_scores[comp] for comp in relationship), 1)
内容的提问来源于stack exchange,提问作者Jerru
相关产品推荐
相关产品推荐

