我正在嘗試遍歷我的字典串列,因為當用戶選擇相應的 ID 時,會將其復制到另一個串列中。
allBooks =[
{'ID': 101, 'title': 'Meditations', 'author': 'Marcus Aurelius', 'year': 180, 'status': True},
{'ID': 102, 'title': 'To Kill a Mockingbird', 'author': 'Harper Lee', 'year': 1960, 'status': True},
{'ID': 103, 'title': 'The Great Gatsby', 'author': 'F. Scott Fitzgerald', 'year': 1925, 'status': True},
{'ID': 104, 'title': 'Don Quixote', 'author': 'Miguel de Cervantes', 'year': 1615, 'status': True},
{'ID': 105, 'title': 'The Little Prince', 'author': 'Antoine de Saint-Exupery', 'year': 180 , 'status': True}
]
booksCheckedOut = []
def menu2():
os.system('clear')
for dic in allBooks:
print(dic)
option = input('\nIf You Want To Go Back Type 0\n\nWhat is the ID? ')
# Going back to Main Menu
if option == '0':
return main_menu()
# If User Proceeds with Checking in
else:
for dic in booksCheckedOut:
for k, v in dic.items():
if option == v:
booksCheckedOut.copy(dic)
return menu2()
else:
return menu2()
我的預期輸出將帶我回到 main_menu()
并復制用戶選擇的字典
booksCheckedOut =['ID': 101, 'title': 'Meditations', 'author': 'Marcus Aurelius', 'year': 180, 'status': True}]
uj5u.com熱心網友回復:
您不需要遍歷字典項。只需將 ID 與用戶輸入的內容進行比較即可。
當 ID 在回圈中不匹配時,您不應該回傳,因為您需要繼續查找。
不要使用遞回呼叫來代替回圈。如果您想回傳主選單,只需從這里回傳(我假設它是從 呼叫的main_menu())。并且要另一本書,只需將此代碼包裝在一個回圈中。
def menu2():
while True:
os.system('clear')
for dic in allBooks:
print(dic)
option = input('\nIf You Want To Go Back Type 0\n\nWhat is the ID? ')
# Going back to Main Menu
if option == '0':
return
# If User Proceeds with Checking in
else:
id = int(option)
for dic in booksCheckedOut:
if dic['ID'] == id:
booksCheckedOut.append(dic)
break
print(f"ID {id} not found")
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/436677.html
上一篇:如何間接訪問類實體屬性?
