我得到了以下代码:
mon = tue = wed = thu = fri = sat = sun = bh = None
for ot in shop_data['opening_time']:
if ot['day'] == 'Monday':
mon = ot
elif ot['day'] == 'Tuesday':
tue = ot
elif ot['day'] == 'Wednesday':
wed = ot
elif ot['day'] == 'Thursday':
thu = ot
elif ot['day'] == 'Friday':
fri = ot
elif ot['day'] == 'Saturday':
sat = ot
elif ot['day'] == 'Sunday':
sun = ot
elif ot['day'] == 'Bank holidays':
bh = ot
ot变量的结构是:
ot = {'day': 'Monday', 'closed': True}
或
ot = {
'day': choices.get(operating_time.day),
'open_time': operating_time.open_time,
'close_time': operating_time.close_time
}
用于描述商店的营业时间,以模板
呈现我想从列表中指定正确的ot以更好的方式更正星期几
这样做的python方式是什么?
修改
这是“星期几”匹配之前的一段代码
shop_operating_time = OperatingTime.objects.filter(
place=place).order_by('day')
shop_operating_time_list = []
choices = dict((x, y) for x, y in DAY_CHOICES)
days = choices.itervalues()
operating_time_day = set()
for operating_time in shop_operating_time:
data = {
'day': choices.get(operating_time.day),
'open_time': operating_time.open_time,
'close_time': operating_time.close_time,
}
shop_operating_time_list.append(data)
operating_time_day.add(choices.get(operating_time.day))
remaing_days = set(days) - operating_time_day
for day in remaing_days:
data = {
'day': day,
'closed': True
}
shop_operating_time_list.append(data)
shop_data = {
'opening_time': shop_operating_time_list
}
答案 0 :(得分:0)
我创建了一个字典,而不是8个变量:
opening_times = {'mon':无,'tue':无,......}
然后您可以根据键轻松分配。您还可以使用课程setattr:
day = 'bh' if ot['day'] == 'Bank Holidays' else ot['day'].lower()[:3]
setattr(opening_times, day, ot)
最后,您甚至可以使用exec(only in Python 2,而且速度很慢!):
exec("%s = ot" % var_name)
修改locals
为not a good idea(感谢DSM!),即使它似乎有效(有时)。