有没有办法将这段代码压缩成更简单的形式或其他方式来做同样的事情?
if h == 0:
day = 'Saturday'
elif h == 1:
day = 'Sunday'
elif h == 2:
day = 'Monday'
elif h == 3:
day = 'Tuesday'
elif h == 4:
day = 'Wednesday'
elif h == 5:
day = 'Thursday'
else:
day = 'Friday'
print('Day of the week is', day)
答案 0 :(得分:5)
您可以使用字典:
days= {
0:'Saturday',
1:'Sunday',
2:'Monday',
3:'Tuesday',
4:'Wednesday',
5:'Thursday'}
print(days.get(h,'Friday'))
使用dict.get
方法的优点是你可以传递一个默认值,如果字典中不存在该键,它将返回。
答案 1 :(得分:2)
创建列表
days = ('Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday')
day = days[h]
print('Day of the week is', day)