【发布时间】:2023-03-02 23:45:01
【问题描述】:
我正在重构意大利面条代码,它有这样一段:
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 次。而且我不会过多地增加行数或创建额外的功能等。
附:我没有写那个代码,所以不要评判我。由于代码中的强耦合,我不能一次做出大的改变。完整代码请查看this link
【问题讨论】:
-
这个字典是静态的,只需要定义一次。在模块级别定义,定义不会被执行两次。你确定它正在运行数百次吗?您至少可以将其移至模块级别。
-
@smido,是的,我确定。它只是代码的一部分。它在执行下一行时发生变化。 “value”、“isIncreased”、“isDecreased”键的所有值都在变化。课程的完整代码在这个链接中:pastebin.com/CLQ7SF9g
-
目前还不是很清楚你在做什么,但也许可以从
collections中检查defaultdict,这可以让你根本不定义结构,只需设置值。你可能需要无限嵌套的字典,命名为InfiniteDicthere -
@smido 我也这么认为,我自己的实现使用 defaultdict。只是想检查是否有更好的东西。感谢您的精力和时间。
标签: python refactoring dry