我正在重构意大利面条式代码,它有这样一段代码:template_dict = { "value": "", "isIncreased": False, "isDecreased": False}my_dict = { "current_half_result": { "home": template_dict, "draw": template_dict, "away": template_dict }, "full_time_result": { "home": template_dict, "draw": template_dict, "away": template_dict }, "current_half_over_under": { "$1_5": { "over": template_dict, "under": template_dict }, "handicap": "" }, "full_time_over_under": { "$2_5": { "over": template_dict, "under": template_dict }, "handicap": "" }, "next_goal": { "home": template_dict, "no_goal": template_dict, "away": template_dict }}如您所见,my_dict 变量在所有叶键中具有相同的值 - template_dict。如何以一种代码不会比当前示例慢的方式从代码中删除重复,并提高代码的可读性和清洁度。速度是一个重要因素,因为这段代码在我的服务器中每秒执行 3-600 次。而且我不会过多地增加行数或创建附加功能等。PS我没有写那个代码,所以不要评判我。由于代码的强耦合性,我不能一下子做出大的改变。
1 回答

繁花如伊
TA贡献2012条经验 获得超12个赞
这是我自己的解决方案。
def_dict = defaultdict(lambda: {"value": "", "isIncreased": False, "isDecreased": False})
my_dict = defaultdict(lambda: def_dict)
# PyCharm raises warning for two lines below, but it works
my_dict['current_half_over_under'] = defaultdict(lambda: def_dict)
my_dict['full_time_over_under'] = defaultdict(lambda: def_dict)
并设置"handicap"键"full_time_over_under"和"current_half_over_under"字典我们应该通过访问它my_dict.setdefault('handicap', some_value)
添加回答
举报
0/150
提交
取消