我如何浓缩所有这些“如果”的陈述?

2022-12-05 03:27:08 发布

您现在位置:Python中文网/ 问答频道 /正文

一般来说,我对python和编程都很陌生,我制作了一个程序,可以让你在今天的日期上加上几天,它会输出该日期。不是很有用,但我对它占用的空间感到非常恼火,我想知道它是否可以变得更小、更简洁,因为它非常简单。我其实一点也不知道。如果有人能给我看,那就太好了

import datetime
calendar = {1:"Sunday", 2:"Monday", 3:"Tuesday", 4:"Wednesday", 5:"Thursday", 6:"Friday", 0:"Saturday"}
Day = eval(input("Enter how many days you want to look into the future: "))
todayDate = datetime.date.today()
x = todayDate.strftime("%A")
if x == "Sunday" :
    y = ((1+ Day) % 7)
    print(calendar[y]) 
    exit()
if x == "Monday" :
    y = ((2+ Day) % 7)
    print(calendar[y]) 
    exit()
if x == "Tuesday" :
    y = ((3+ Day) % 7)
    print(calendar[y]) 
    exit()
if x == "Wednesday" :
    y = ((4+ Day) % 7)
    print(calendar[y]) 
    exit()
if x == "Thursday" :
    y = ((5+ Day) % 7)
    print(calendar[y]) 
    exit()
if x == "Friday" :
    y = ((6+ Day) % 7)
    print(calendar[y]) 
    exit()
if x == "Saturday" :
    y = ((7+ Day) % 7)
    print(calendar[y]) 
    exit()


Tags: datetimeif编程exitcalendarprintmondaydaysundayfridaysaturdaywednesdaythursdaytuesdaytodaydate
3条回答
offset = {d: o for o, d in calendar.items()}
y = (offset[x] + day) % 7
print(calendar[y])

您可以使用timedelta向日期添加任意数量的时间

from datetime import date, timedelta

x=5#or any amount of days you want
date = date.today()
new_date=date+timedelta(days=x)
print(new_date.strftime('%A'))

如果您不希望创建一个反向字典,那么您可以使用自己的代码执行多种操作

  • 不要重复(打印和退出可以在if语句之后完成
  • 使用elif避免不必要地检查if语句(尽管目前单独的出口不会出现这种情况)
x = todayDate.strftime("%A")
if x == "Sunday" :
    y = ((1+ Day) % 7)
elif x == "Monday" :
    y = ((2+ Day) % 7)
elif x == "Tuesday" :
    y = ((3+ Day) % 7)
elif x == "Wednesday" :
    y = ((4+ Day) % 7)
elif x == "Thursday" :
    y = ((5+ Day) % 7)
elif x == "Friday" :
    y = ((6+ Day) % 7)
elif x == "Saturday" :
    y = ((7+ Day) % 7)
print(calendar[y]) 
exit()

Python3.10将带来^{} statement,这将使它稍微更高效

x = todayDate.strftime("%A")
match x:
    case "Sunday" :
        y = ((1+ Day) % 7)
    case "Monday" :
        y = ((2+ Day) % 7)
    case "Tuesday" :
        y = ((3+ Day) % 7)
    case "Wednesday" :
        y = ((4+ Day) % 7)
    case "Thursday" :
        y = ((5+ Day) % 7)
    case "Friday" :
        y = ((6+ Day) % 7)
    case "Saturday" :
        y = ((7+ Day) % 7)