我的代码:
def readData(fname):
year = []
loc = []
with open(fname) as f:
for line in f.read():
curr_line = line.split('\t')
print(curr_line)
year.append(curr_line[0])
loc.append(curr_line[1])
return (year,loc)
def findLocation(yrList,locList,year):
yrList = [str(yr) for yr in yrList]
if year not in yrList:
return "Not found."
return locList[yrList.find(str(year))]
def main():
yr, loc = readData('olympics.txt')
print(yr)
print(loc)
x = input("Enter year: ")
print(findLocation(yr,loc,x))
执行main()函数后,在输入年份后给出了这个错误
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
main()
File "C:\Users\MyName\Downloads\Homework5.py", line 25, in main
print(findLocation(yr,loc,x))
File "C:\Users\MyName\Downloads\Homework5.py", line 18, in findLocation
return locList[yrList.find(year)]
AttributeError: 'list' object has no attribute 'find'
有人可以解释我的代码有什么问题吗?为什么我会收到此错误?
答案 0 :(得分:0)
编写我的解决方案作为答案而不仅仅是对未来访问者的评论:
如果要在列表中查找值的索引,可以使用yrList.index(year)
,它将返回列表中元素的索引或抛出您必须捕获的ValueError,而不是不存在的.find
。