【问题标题】:Python Files IndexErrorPython 文件索引错误
【发布时间】:2016-06-16 00:41:45
【问题描述】:

我的代码:

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'

谁能解释我的代码有什么问题以及为什么会出现这个错误?

【问题讨论】:

  • 请修正你的缩进并从那堵不属于问题的文本墙中删除所有内容。
  • 你需要告诉我们你真正想要做什么(而不是你的作业问题是什么)。运行程序时会发生什么?
  • 如果遇到异常,我们确实需要查看异常的完整回溯。 (我们可能根本不需要知道作业。)
  • 这信息太多了,你能把它缩减到问题的相关部分吗?
  • 错误出现在哪一行?

标签: python


【解决方案1】:

将我的解决方案写成答案,而不仅仅是对未来访问者的评论:

如果您正在查找列表中某个值的索引,您可以使用yrList.index(year),它要么返回列表中元素的索引,要么抛出一个您必须捕获的 ValueError,而不是.find 不存在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-01
    • 2021-04-20
    • 2017-02-23
    • 2016-05-14
    • 2018-02-22
    • 1970-01-01
    • 2019-03-03
    • 2014-01-27
    相关资源
    最近更新 更多