TypeError:列表索引必须是整数,而不是str。了解问题,而不是ans

2024-05-01 21:30:32 发布

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

独特的情况下,我知道的问题,只是不知道一个解决办法

import string

timefile = open('lasttimemultiple.txt','r+')#opens the file that contains the        last time run
lasttime = timefile.read()#reads the last time file
items= int(2)

splitlines = string.split(lasttime,'\n')
print splitlines[items][0:2]
timefile.close() #closes last time
PullType = '00'
datapt = '01'
for items in splitlines:
if splitlines[items][0:2] == PullType:
    datapt = splitlines[items]
else:
    print ''

print datapt

我知道我的问题是我使用'items'作为我调用的索引而不是整数,但是我不知道如何使用引用来处理数据而不使用非int变量名

有什么办法可以做到这一点吗? 谢谢


Tags: thestringtime情况itemsfileintlast
1条回答
网友
1楼 · 发布于 2024-05-01 21:30:32

你应该显示实际的回溯。如果有,您会看到错误在这行:

if splitlines[items][0:2] == PullType:

这是因为这里的items已经被前一行中的for循环重新定义了。在Python的for循环中,变量不是计数器,而是该迭代中的实际项。所以,在第一次迭代中,items是splitlines的第一个元素,等等,所以它是一个字符串,而不是一个整数。解决方法是直接使用它:

if items[0:2] == PullType:

(另外,您应该考虑更好的变量名:应该是item,而不是items

相关问题 更多 >