求教一下,如何将for循环转成推导式
import time
import datetime
# 列表推导式{表达式 for item in 可迭代对象 if 条件判断}
shop_name = '1315a1321b1409c1421d79'
shop_date = []
for x in range(5):# 生成日期
b = (datetime.datetime.now() + datetime.timedelta(days=-3 + x)).strftime("%m%d")[-2:]# 循环5天内日期,每次循环+1天(x),从前三天开始,每次结果赋值给 b
if shop_name[0:2] == b:# 判断循环结果 b 是否与 shop_name 前两个字符相同,相同则将完整日期赋值给 shop_date
shop_date = (datetime.datetime.now() + datetime.timedelta(days=-3 + x)).strftime("%Y-%m-%d")
break
print(shop_date)
本帖最后由 川黔 于 2021-1-14 19:40 编辑
import time
import datetime
# 列表推导式{表达式 for item in 可迭代对象 if 条件判断}
shop_name = '1315a1321b1409c1421d79'
shop_date = [(datetime.datetime.now() + datetime.timedelta(days=-3 + x)).strftime("%Y-%m-%d") for x in range(5) if shop_name ==(datetime.datetime.now() + datetime.timedelta(days=-3 + x)).strftime("%m%d")[-2:]]
print(shop_date)
页:
[1]