列表标记必须是整数或片,而不是datetime.datetime

2024-06-16 11:14:14 发布

您现在位置:Python中文网/ 问答频道 /正文

很抱歉,我是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'))

Tags: 代码用户infordatetimeif定义错误
2条回答
for checkexp in dates:
   #checkexp = dates[d]
   if checkexp + timedelta(days = 7) < current:
        print('Food will expire within a week')

您使用的是for-each循环构造。当对iterable执行for x in iterable时,x这里不是索引,而是元素本身。因此,当您运行for d in dates时,Python返回的是日期中的datetime对象,而不是索引

相反,你必须做到:

for checkexp in dates:
   if checkexp + timedelta(days = 7) < current:
        print('Food will expire within a week')

或者,如果同时需要索引和元素,可以使用enumerate函数

for i, checkexp in enumerate(dates):
    # You can access the element using either checkexp or dates[i].
    if checkexp + timedelta(days = 7) < current:
        print('Food will expire within a week')

如果必须使用索引,则可以使用len函数获取iterable的长度,并像在C中一样访问列表元素。但这不是Pythonic

for i in range(len(dates)):
   if dates[i] + timedelta(days = 7) < current:
        print('Food will expire within a week')

相关问题 更多 >