簡體   English   中英

我正在通過字典建立關系,但是有人可以幫我解決一個我不知道的輸出嗎?

[英]I am making relationships from a dictionary, but can someone help me fix one output I can't figure out?

我想做的是制作一本我成功完成的祖先詞典。 我唯一的問題是當不存在關系時,我的程序應輸出“該關系不在詞典中”。 當鍵不在字典中時,我知道該怎么做,但是如何使用值呢?

這是我的代碼:

relationships = {"Jalen": "Joseph", "Arthur": "Joseph", "Mike": "Joseph", "Chris": "Joseph", "Joseph": "Thomas", "Jesse": "Marcus", "Marcus": "Gerhard", "Gerhard": "Allan", "Allan": "Thomas", "James": "Gerhard"}
print relationships

def menu():
    print ("To find a father, press 1.")
    print ("To find a grandfather, press 2.")
    print ("To find a great-grandfather, press 3.")
    print ("To exit the program, press 0,")
    while True:
        choice = input("Enter your choice of action: ")
        if (choice >= 0) and (choice <= 3):
            return choice
        else:
            print("Invalid option. Enter an integer from 0 to 3")

def father(n):
    if relationships.has_key(n):
        return relationships[n]

def grandfather(n):
    if relationships.has_key(n):
        father = relationships[n]
        if relationships.has_key(father):
            return relationships[father]

def greatgrandfather(n):
    if relationships.has_key(n):
        father = relationships[n]
        if relationships.has_key(father):
            grandfather = relationships[father]
            if relationships.has_key(grandfather):
                return relationships[grandfather]

def main ():
    while True:
        choice = menu()
        if choice == 0:
            break
        else:
            name = raw_input("Please enter the name of the person for whom you seek an ancestory: ")
            if relationships[name]:
                if choice == 1:
                    print "The father of ", name, " is ", father(name), "."
                elif choice == 2:
                    print "The grandfather of ", name, " is ", grandfather(name), "."
                else:
                    print "The great-grandfather of ", name, " is ", greatgrandfather(name), "."
            else:
                print "This relationship is not in our records."


main()

如何檢查值中是否存在關系? Python語言。

in關鍵字用於檢查值或鍵是否在字典中。 因此,您需要檢查字典中是否存在鍵的所有操作是:

if record not in relationships:
    print "This relationship is not in our records.
if aRelationship in relationships.values():
    #aRelationship in relationships.values()
else:
    #aRelationship  not in relationships.values()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM