2016-03-02 64 views
-7

我的代碼:Python文件IndexError

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' 

有人可以解釋什麼是錯我的代碼爲什麼我得到這個錯誤?

+1

請修復您的縮進並去除不屬於該問題的文本牆的所有內容。 – timgeb

+1

你需要告訴我們你實際上想要做什麼(而不是你的家庭作業問題)。當你運行程序時會發生什麼? – DaveBensonPhillips

+0

如果您遇到異常,我們確實需要查看異常的完整回溯。 (我們可能根本不需要知道任務。) – Blckknght

回答

0

寫我的解決方案作爲一個答案,而不僅僅是爲未來的參觀者留言:

如果你正在尋找一個列表中值的索引可以使用yrList.index(year),這將要麼返回的索引元素在列表中或拋出一個ValueError,你必須趕上,而不是.find,不存在。