在循环中使用多个条件的Python

2024-04-26 04:23:04 发布

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

我试图在if-else表达式中使用多个条件,如下所示:

from datetime import date, timedelta as td, datetime
import holidays

st_dt = '1/1/2017'
en_dt = '1/5/2017'

st_year = datetime.strptime(st_dt, "%m/%d/%Y").year
en_year = datetime.strptime(en_dt, "%m/%d/%Y").year
st_mnth = datetime.strptime(st_dt, "%m/%d/%Y").month
en_mnth = datetime.strptime(en_dt, "%m/%d/%Y").month
st_date = datetime.strptime(st_dt, "%m/%d/%Y").day
en_date = datetime.strptime(en_dt, "%m/%d/%Y").day

d1 = datetime(st_year, st_mnth, st_date, 0, 0, 0)
d2 = datetime(en_year, en_mnth, en_date, 0, 0, 0)

AllHours = []
i = 0
while(d1<=d2):
    AllHours.append(d1)
    d1 = d1 + td(hours=1)

us_holidays = holidays.UnitedStates()
HolidayWorkingDay = ['H' if x in us_holidays else 'W' for x in AllHours]
HE = [x.hour for x in AllHours]    
DayDefn = ['Type1' if (x == 'H' and y>=7 and y<=23) else 'Type2' for x in HolidayWorkingDay and for y in HE]

所以,在上面,我试图确保如果列表中的某个位置HolidayWorkingDay和他符合某些标准,我给他们取名为“Type1”,否则他们就是“Type2”

但是由于语法错误,它在最后一行失败了。我不知道写多重表达式的正确方法是什么


Tags: infordatetimedateifdtholidaysyear
1条回答
网友
1楼 · 发布于 2024-04-26 04:23:04

如果需要嵌套循环,应该这样编写最后一个列表(不带and):

DayDefn = ['Type1' if (x == 'H' and y>=7 and y<=23) else 'Type2'
           for x in HolidayWorkingDay for y in HE]

相关问题 更多 >