我试图在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和HE列表中的某个位置符合某些条件,我给它们命名为'Type1',否则它们是'Type2'
但由于语法错误,它在最后一行失败了。我不确定写多个表达式的正确方法是
答案 0 :(得分:1)
如果你想要嵌套循环,你应该写这样的最后一个列表理解(没有and
):
DayDefn = ['Type1' if (x == 'H' and y>=7 and y<=23) else 'Type2'
for x in HolidayWorkingDay for y in HE]