如何简化包含许多if-else语句的python代码



所以我有这段代码,但我不想使用很多if else条件,我想知道是否可以简化它。有什么想法吗?我可以用一个循环吗?

if dh1['date1'][0].strftime("%A") == 'Monday':
df=df=pd.concat([dh1,dh2.tail(84)])
df=df.sort_values(['date1','hr1'])
df=df.reset_index()
df=df.drop('index', 1)
elif dh1['date1'][0].strftime("%A") == 'Tuesday':
df=df=pd.concat([dh1,dh2.tail(96)])
df=df.sort_values(['date1','hr1'])
df=df.reset_index()
df=df.drop('index', 1)
elif dh1['date1'][0].strftime("%A") == 'Wednesday':
df=df=pd.concat([dh1,dh2.tail(108)])
df=df.sort_values(['date1','hr1'])
df=df.reset_index()
df=df.drop('index', 1)
elif dh1['date1'][0].strftime("%A") == 'Thursday':
df=df=pd.concat([dh1,dh2.tail(120)])
df=df.sort_values(['date1','hr1'])
df=df.reset_index()
df=df.drop('index', 1)
elif dh1['date1'][0].strftime("%A") == 'Friday':
df=df=pd.concat([dh1,dh2.tail(132)])
df=df.sort_values(['date1','hr1'])
df=df.reset_index()
df=df.drop('index', 1)
elif dh1['date1'][0].strftime("%A") == 'Saturday':
df=df=pd.concat([dh1,dh2.tail(144)])
df=df.sort_values(['date1','hr1'])
df=df.reset_index()
df=df.drop('index', 1)
elif dh1['date1'][0].strftime("%A") == 'Sunday':
df=df=pd.concat([dh1,dh2.tail(156)])
df=df.sort_values(['date1','hr1'])
df=df.reset_index()
df=df.drop('index', 1)
所有分支之间的唯一区别似乎是传递给tail方法的参数。此外,相邻天数的自变量值之间的差为12,因此可以将其评估为从周一开始计数为084 + 12 * weekday。如果真的是这样的话,你可以减少这样的代码:
arg = 84 + dh1['date'][0].weekday() * 12
df=df=pd.concat([dh1,dh2.tail(arg)])
df=df.sort_values(['date1','hr1'])
df=df.reset_index()
df=df.drop('index', 1)

唯一的区别是df.tail参数,它取决于date1列。每当出现这些情况时,您都会创建如下映射。

tail_day_map = {
'Monday': 84,
'Tuesday': 96,
'Wednesday': 108,
'Thursday': 120,
'Friday': 132,
'Saturday': 144,
'Sunday': 156
}
def perform_action(df, tail_day_map):
tail_number = tail_day_map[df['date1'][0].strftime("%A")]
df = df.tail(tail_number)
df = df.sort_values(['date1','hr1'])
df = df.reset_index()
df = df.drop('index', 1)
return df

如果您能够使用Python 3.10或更高版本,那么使用Match Case如何?https://learnpython.com/blog/python-match-case-statement/

Match Case可能会简化代码并提供更高的可读性,但正如第二个链接中所提到的,要谨慎处理案例的顺序,因为它可能会改变逻辑的行为。

否则,您可能会使用其他流量控制策略:https://docs.python.org/3/tutorial/controlflow.html

dict = {
"Monday": 84,
"Tuesday": 96,
...
}

你可以在这里使用字典

首先,
df=df=pd.concat([dh1,dh2.tail(156)])可能是
df=pd.concat([dh1,dh2.tail(156)])
然后,

df=df.sort_values(['date1','hr1'])
df=df.reset_index()
df=df.drop('index', 1)

可以排除if条件
那么对我来说,
我会做一个dict,比如:d = {"Monday":84,"Tuesday":96...}在条件外使用:

weekday = dh1['date1'][0].strftime("%A")
df=pd.concat([dh1,dh2.tail(d[weekday])])

所以最后的代码是:

d = {"Monday":84,"Tuesday":96...}
weekday = dh1['date1'][0].strftime("%A")
df=pd.concat([dh1,dh2.tail(d[weekday])])
df=df.sort_values(['date1','hr1'])
df=df.reset_index()
df=df.drop('index', 1)

最新更新