Python Lambda if 语句

Python Lambda if statements

我正在尝试列出与月份对应的天数,我需要考虑闰年,我希望能够访问 28 天或 29 天,具体取决于是否是闰年.这是我的:

def code(x)
    monthdays = [31, lambda x: 28 if leapyear(x) == False else 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    return months[1]

leapyear() 只是一个带有 1 个参数的函数,return如果是闰年则为 True,否则为 False。由于某些原因,return 不是我想要的数字。我还能怎么做?

您在这里不需要 lambda(而且您并不是 调用 它),一个简单的条件表达式就可以解决问题。试试这个:

monthdays = [31, 29 if leapyear(x) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

另外,我相信你在最后一行的意思是:

return monthdays[1]

…否则,如果我们不打算使用它,创建 monthdays 有什么意义呢?更重要的是,如果我们只对一个职位感兴趣,为什么要创建一个完整的列表?

如果您想准确了解什么是闰年和日历事件,建议使用calendar.monthrange。你可以这样使用它:

from calendar import monthrange

year = 2015
days = []
for month in range(1,13):
    days.append(monthrange(year, month)[1])

print(days)

其中 returns 包含给定年份每个月的天数的列表:

[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

如果您只想要 2 月的天数,您可以计算:

from calendar import monthrange

year = 2015
feb_days = monthrange(year, 2)[1]
print(feb_days)