python - 我试图在多维列表中找到一个特定的值。但是当我试图找到那个特定的值时,我的函数将什么也不返回
问题描述
所以我试图在我的列表中搜索用户指定的电影评级,但每次我指定一个评级来搜索我的函数时都不会返回任何内容。
例如:当它提示我输入要查找的评级时。我将输入“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']]
解决方案
您的代码没有什么特别的问题。
但是,您L
的 ' 格式是错误的。
['"Detective Pikachu",104,PG', '']
其中只有 2 个元素。
元素0
是"Detective Pikachu",104,PG
元素1
是。
您应该修复getInput()
解析的方式movies.txt
或更改函数以读取L
.
此外,您应该close()
使用后的文件。
推荐阅读
- elasticsearch - 如何使用 Postman 和 ElasticSearch 向请求正文添加过滤器?
- ios - 无法使用 safari 打开某些网站
- c# - 如何模拟嵌套接口?
- javascript - vis.js 库 - 使用 svg 和自定义 html 渲染节点网络
- javascript - 使用 node.js 管理多个 Websocket 客户端连接
- jquery - Turbolinks-5 返回访问其他页面的页面后未重新加载 Javascript 代码
- r - 在估算的数据框中包含 ID 变量
- python - Plotnine:绘制图形时如何删除 ggplot:(xxx) 类型烦人的文本输出
- heroku - 桌面 Neo4j 错误:无法在数字“0”上创建属性“传输类”
- r - 在ggplot2中更改分组条形图的颜色