为什么我得到“列表索引超出范围”错误?

时间:2016-06-04 16:52:25

标签: python indexoutofboundsexception

这是我的计划:

   def FoundmovieNamesInQuery(userQueryPart,nameOfMovie):
        for userQueryPart in userQuery:
            for nameOfMovie in movieNames:
                if userQueryPart == nameOfMovie:
                    return True
        return False


    print("welcome")
    userQuery = input("use our quick search to find cinema times for films shwing today: ").lower().split()
    print(userQuery)

    with open("movies.txt")as file:
        lines = file.readline()
    slutionFound = False

    for line in lines:
        item = line.split(":")
        movieNames = item[0].split()
        movieTimes = item[1]
        if FoundmovieNamesInQuery():
            print(movieTimes)
            solutionFound = True
    if solutionFound == False:
        print("movie not found.\n please call us on 0800 020 030")

但是当我运行它时会出现以下错误消息:

welcome
use our quick search to find cinema times for films shwing today: annabelle
['annabelle']
Traceback (most recent call last):
  File "C:\Users\FARUQE TALUKDAR\Downloads\online film.py", line 20, in <module>
    movieTimes = item[1]
IndexError: list index out of range

这是我的文字档案:

run along : this movie will be showing at 18.00
annabelle : this movie will be showing at 13.00
x-men : this movie will be showing at 7.00

1 个答案:

答案 0 :(得分:1)

首先,您需要使用def translate(a): trs = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"ar"} translated = [] for i in a.split(" "): if i in trs: translated.append(trs[i]) return " ".join(translated) print translate("merry christmas and happy new year") # prints "god jul och gott nytt ar" 而不是readlines,它会读取整个txt。

其次,您需要将参数传递给功能readline

FoundmovieNamesInQuery(userQuery, movieNames)