有什么方法可以总结以下代码吗?每个if-else条件后面的代码非常相似。唯一的区别是传递给relativedelta
的参数。
def change_datetime_objects(dt_objs=[], resolution="year", frequency=1):
new_dt_list = []
if resolution="year":
for time_obj in dt_objs:
new_dt_list.append(time_obj + relativedelta(years=frequency))
elif resolution="month":
for time_obj in dt_objs:
new_dt_list.append(time_obj + relativedelta(months=frequency))
elif resolution="week":
for time_obj in dt_objs:
new_dt_list.append(time_obj + relativedelta(weeks=frequency))
elif resolution="day":
for time_obj in dt_objs:
new_dt_list.append(time_obj + relativedelta(days=frequency))
elif resolution="hour":
for time_obj in dt_objs:
new_dt_list.append(time_obj + relativedelta(hours=frequency))
elif resolution="minute":
for time_obj in dt_objs:
new_dt_list.append(time_obj + relativedelta(minutes=frequency))
elif resolution="second":
for time_obj in dt_objs:
new_dt_list.append(time_obj + relativedelta(seconds=frequency))
附言:我想也许eval()
、exec()
甚至装饰师可以帮助创建new_dt_list.append(time_obj + relativedelta(<>=frequency))
的通用形式,但不知道他们能提供什么帮助。
我在这篇文章的启发下找到了问题的答案。
因此,基本上为了避免所有冗余,参数应该在之前作为字典生成,并使用**
作为关键字参数传递给函数。
def change_datetime_objects(dt_objs=[], resolution="year", frequency=1):
args = {resolution: frequency}
new_dt_list = []
for time_obj in dt_objs:
new_dt_list.append(time_obj + relativedelta(**args))