2 回答

TA貢獻(xiàn)1866條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以首先收集列表中的所有對(duì)象引用號(hào)
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")
要顯示有關(guān)對(duì)象的更多信息,您可以先收集所有對(duì)象
objects = initialize()
然后,分別收集你需要的關(guān)于每個(gè)對(duì)象的信息
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]
請(qǐng)注意obj.title,obj.rating和obj.author是如何提取對(duì)象屬性的示例。我不知道確切的屬性名稱,因此您需要用正確的名稱替換title、rating和author。
然后,檢查用戶輸入的參考編號(hào),如果匹配,則打印信息
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)返回輸入的參考編號(hào)的索引,使用該索引,您可以從各自的列表中提取標(biāo)題、評(píng)級(jí)和作者(例如obj_titles[obj_id])。
完整的函數(shù)如下所示:
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貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超7個(gè)贊
您可以使用列表理解并使用not in而不是for單獨(dú)遍歷所有對(duì)象。
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')
添加回答
舉報(bào)