列表索引必须是整数或切片,而不是 datetime.datetime

抱歉,我提出了一个菜鸟问题,我是 python 新手,所以这是我的问题:


当尝试运行以下代码时,使用用户在前面的代码中定义的日期[0],例如 -


dates.append(2020 8 25)


   for d in dates:

   checkexp = dates[d]

   if checkexp + timedelta(days = 7) < current:

        print('Food will expire within a week')

我收到错误: list indices must be integers or slices, not datetime.datetime


我可能只是犯了一个初学者的错误,但我们将不胜感激!


值得一提的是,代码在这之前运行:


firstdate = dates[0]

print(firstdate.strftime('%d/%m/%y'))


HUWWW
浏览 140回答 2
2回答

慕妹3146593

您正在使用 for-each 循环结构。for x in iterable当您对可迭代对象执行 a 时,x这里不是索引,而是元素本身。因此,当您运行 时for d in dates,Python 将返回datetime日期中的对象,而不是索引。相反,你必须这样做:for checkexp in dates:&nbsp; &nbsp;if checkexp + timedelta(days = 7) < current:&nbsp; &nbsp; &nbsp; &nbsp; print('Food will expire within a week')或者,如果您想要索引和元素,则可以使用该enumerate函数。for i, checkexp in enumerate(dates):&nbsp; &nbsp; # You can access the element using either checkexp or dates[i].&nbsp; &nbsp; if checkexp + timedelta(days = 7) < current:&nbsp; &nbsp; &nbsp; &nbsp; print('Food will expire within a week')如果必须使用索引,则可以使用该len函数来获取可迭代的长度,并像在 C 中一样访问列表元素。但这不是 Pythonic。for i in range(len(dates)):&nbsp; &nbsp;if dates[i] + timedelta(days = 7) < current:&nbsp; &nbsp; &nbsp; &nbsp; print('Food will expire within a week')

慕田峪4524236

for checkexp in dates:&nbsp; &nbsp;#checkexp = dates[d]&nbsp; &nbsp;if checkexp + timedelta(days = 7) < current:&nbsp; &nbsp; &nbsp; &nbsp; print('Food will expire within a week')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python