[英]How can I only use one dictionary and be able to output a third value related to the key pair?
我的講師給我布置了一項任務,要完成幾個挑戰,以幫助我提高對詞典及其背后概念的理解。 我已經能夠很容易地完成第一個任務,但我對第二個任務非常堅持。 第一個任務是創建一個“誰是你爸爸? 程序'。
挑戰說明:編寫一個 Who's Your Daddy 程序,讓用戶輸入一個男性的名字並產生他父親的名字。 (您可以使用名人、虛構人物甚至歷史人物來取樂。)允許用戶添加、替換和刪除父子對。
我只能通過一個問題來創造這一挑戰,即我只能替換一個兒子的父親,而不是兩者兼而有之。
第二個挑戰是:通過添加一個選項來改進這個程序,讓用戶輸入一個名字並找回祖父。 你的程序仍然應該只使用一本父子對的字典。 確保在您的字典中包含幾代,以便可以找到匹配項。
我認為我可以使用嵌套在字典中的字典並對其進行研究,但它只說明了一個字典。 然后我想我是否可以在字典中使用一個元組,然后當用戶請求一個兒子和他們的祖父時訪問這個元組,但也沒有太多運氣,所以我決定來這里。
所以現在我想知道,如何為每一對添加祖父,你可以為字典中的鍵添加第二個值嗎?
names = { "henry" : "michael",
"louis" : "jason",
"owen" : "justin",
"jake" : "glynn",
"adam" : "mark",
}
choice = None
while choice != "0":
print(
"""
Welcome to the Who's Your Daddy? program.
You can find out a father of the names listed,
you can then add, replace and delete a son/father pair.
0 - Exit
1 - List sons and their fathers
2 - Add a pair
3 - Replace a pair
4 - Delete a pair
"""
)
choice = input("Choice: ")
#exit
if choice == "0":
print("Goodbye")
#List sons
if choice == "1":
print(*names.keys(), sep='\n')
son_choice = input("Who's father would you like to know the name of?: ")
if son_choice in names:
print(names[son_choice])
else:
print("That name is not in the list!")
#Add a pair
elif choice == "2":
son_add = input("Enter the name of someone: ").lower()
if son_add not in names:
father_add = input("Now enter the name of their father: ").lower()
names[son_add] = father_add
print("That pair has been added")
else:
print("That name already exists!")
#Replace a pair
elif choice == "3":
son_replace = input("What name do you want to replace?: ")
if son_replace in names:
father_replace = input("Enter the name of their father: ")
names[son_replace] = father_replace
print("The pair has been replaced")
else:
print("That name doesn't exist, please add it first!")
#Delete a pair
elif choice == "4":
son_delete = input("What name do you want me to delete?: ")
if son_delete in names:
del names[son_delete]
print("Pair deleted!")
else:
print("That pair does not exist!")
else:
print("Sorry, that's an invalid choice!")
input("\n\nPress the enter key to exit!")
在 Ronald 的幫助和一點常識的幫助下,我現在已經解決了這個問題。
為了找到祖父,我需要創建一個新的兒子父親對,其中兒子的父親將是已經在列表中的兒子。 例如,如果我創建一個新對,兒子被稱為湯姆,父親被稱為亨利。 然后我可以使用查找祖父 function 來表明湯姆的祖父是邁克爾。
#Find a grandfather
elif choice == "5":
grandson = input("Please enter the son and I will find the grandfather: ").lower()
if grandson in names:
father = names[grandson]
if father in names:
grandfather = names[father]
print("The grandfather of " + grandson + " is " + grandfather)
else:
print(father + " is not in the dictionary")
else:
print(grandson + " is not in the dictionary")
這是我創建的代碼,但是,我將如何使它工作幾代,或者已經由這段代碼完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.