2 回答
TA贡献1789条经验 获得超10个赞
字典没有排序,所以你不能保证你的 day_of_week 键会以正确的顺序迭代。更好的方法是使用 datetime 模块和 timedelta。像这样:
start = datetime.date(2019, 6, 27)
duration = 3 # days
days = [(start + datetime.timedelta(days=n)).strftime('%A') for n in range(duration)]
assert days == ['Thursday', 'Friday', 'Saturday']
TA贡献1921条经验 获得超9个赞
首先,我会以day_of_week这种方式启动:
day_of_week = {0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3: 'Thursday', 4: 'Friday', 5: 'Saturday', 6: 'Sunday'}
您可以从您当前的定义中实现这一点,如下所示:
day_of_week = {v:k for k,v in day_of_week.items()}
然后
import datetime
my_week_day = datetime.datetime(2019,6,27).weekday()
offer_length = 3
offer_days = [v for k,v in day_of_week.items() if k in [a%7 for a in range(my_week_day,my_week_day + offer_length)]]
print(offer_days)
输出: ['Thursday', 'Friday', 'Saturday']
或者您可以使用以下内容来维护正确的日期顺序
offer_days = []
for a in range(my_week_day,my_week_day + offer_length):
offer_days.append(day_of_week[a%7])
print(offer_days)
我只导入了 datetime 因为我不知道你的 test_case 函数。
添加回答
举报