首页 > 解决方案 > 我试图在多维列表中找到一个特定的值。但是当我试图找到那个特定的值时,我的函数将什么也不返回

问题描述

所以我试图在我的列表中搜索用户指定的电影评级,但每次我指定一个评级来搜索我的函数时都不会返回任何内容。

例如:当它提示我输入要查找的评级时。我将输入“PG”,它不会返回任何内容。尽管我知道有些电影是 PG 级的。

我认为问题可能出在我的评分功能或我如何创建我的多维列表中。

下面是我的代码。任何帮助表示赞赏。谢谢!

def getInput():
  try:
    inFile = open("movies.txt", 'r')
  except IOError:
    print("File cannot be found. Check Spelling.")
  else:
    return inFile.readlines()

def menu():
  L = getInput()
  for i in range(0, len(L)):
    L[i] = L[i].split('\n')
  while(True):
    print("\nWelcome to the movie finder!")
    print("\t1. Print the Movies alphabetically by name.")
    print("\t2. Print movies with a rating matching yours.")
    print("\t3. Print the movies by run time.")
    print("\t4. Find all movies with a run time less than your desired time.")
    print("\t5. Find all movies with a run time greater than your desired time.")
    print("Type -1 to quit.")
    opt = input("Input a number to start desired search: ")

    if (int(opt) == 1):
      alpha(L)
    elif (int(opt) == 2):
      rating(L)
    elif (int(opt) == 3):
      runTime(L)
    elif (int(opt) == 4):
      lessThan(L)
    elif (int(opt) == 5):
      greaterThan(L)
    elif (int(opt) == -1):
      break;
    else:
      print("Invalid Input")

def alpha(L):
  L.sort()
  print("\n",L)

def rating(L):
  userRate = str(input("Enter a rating to search for: "))
  for i in range(0, len(L)):
    for j in range(len(L[i])):
      if userRate == L[i][2]:
        print(L[i][0])

menu()

这就是 L(我的多维列表的样子)

[['"Detective Pikachu",104,PG', ''], ['"The Secret Life of Pets 2",86,PG', ''], ['"Deadpool 2",119,R', ''], ['"Godzilla: King of the Monsters",132,PG-13', ''], ['"A
vengers: Endgame",181,PG-13', ''], ['"The Lion King(1994)",88,G']]

标签: pythonmultidimensional-arrayrepl.it

解决方案


您的代码没有什么特别的问题。
但是,您L的 ' 格式是错误的。

['"Detective Pikachu",104,PG', '']

其中只有 2 个元素。
元素0"Detective Pikachu",104,PG
元素1

您应该修复getInput()解析的方式movies.txt或更改函数以读取L.

此外,您应该close()使用后的文件。


推荐阅读