2 回答
TA贡献1866条经验 获得超5个赞
您可以首先收集列表中的所有对象引用号
obj_references = [obj.reference for obj in initialize()]
然后检查是否匹配:
def search_item():
referencenum=input("Enter item reference:")
obj_references = [obj.reference for obj in initialize()]
if referencenum not in obj_references:
print("No Such Object found")
要显示有关对象的更多信息,您可以先收集所有对象
objects = initialize()
然后,分别收集你需要的关于每个对象的信息
obj_references = [obj.reference for obj in objects]
obj_titles = [obj.title for obj in objects]
obj_ratings = [obj.rating for obj in objects]
obj_authors = [obj.author for obj in objects]
请注意obj.title,obj.rating和obj.author是如何提取对象属性的示例。我不知道确切的属性名称,因此您需要用正确的名称替换title、rating和author。
然后,检查用户输入的参考编号,如果匹配,则打印信息
if referencenum not in obj_references:
print("No Such Object found")
else:
obj_id = obj_references.index(referencenum)
print("Title:", obj_titles[obj_id], "Rating:", obj_ratings[obj_id],
"Author:", obj_authors[obj_id])
obj_id = obj_references.index(referencenum)返回输入的参考编号的索引,使用该索引,您可以从各自的列表中提取标题、评级和作者(例如obj_titles[obj_id])。
完整的函数如下所示:
def search_item():
referencenum = input("Enter item reference:")
objects = initialize()
obj_references = [obj.reference for obj in objects]
obj_titles = [obj.title for obj in objects]
obj_ratings = [obj.rating for obj in objects]
obj_authors = [obj.author for obj in objects]
if referencenum not in obj_references:
print("No Such Object found")
else:
obj_id = obj_references.index(referencenum)
print("Title:", obj_titles[obj_id], "Rating:", obj_ratings[obj_id],
"Author:", obj_authors[obj_id])
TA贡献1804条经验 获得超7个赞
您可以使用列表理解并使用not in而不是for单独遍历所有对象。
def search_item():
reference_num = input("Enter item reference:")
if reference_num not in [obj.reference for obj in initialize()]:
print('No such object found')
添加回答
举报