簡體   English   中英

如何使用用戶輸入的關鍵字提取整個列表?

[英]How do I pull an entire list using keywords that the user inputs?

基本上,我有一個簡單的 function 讓用戶輸入信息以創建記錄,然后我希望用戶能夠從“姓氏”調用特定列表並顯示與之關聯的整個列表。 我嘗試使用 if 函數,但 index 可能會更好,因為它是一個列表? 我不知道。 有小費嗎?

    def main():
    print("""
    **********************************************
                 RECORDS MANAGER
    **********************************************
        1.Create a record
        2.Show a record(s) [Enter a Last Name]:
        3.Delete a record [Enter a Last Name]:
        4.Display All Records [Ascending Order]:
        5.Exit
        """)


record = []

ans = True


def create():
    student_id = str(input("Enter the student ID: "))
    firstname = str(input("Enter the First name: "))
    lastname = str(input("Enter the Last name: "))
    age = str(input("Enter the Age: "))
    address = str(input("Enter the Address: "))
    phone_number = str(input("Enter the Phone number: "))
    si = student_id
    fn = firstname
    ln = lastname
    a = age
    adr = address
    pn = phone_number
    name = f"StudentID: {si}, First name: {fn}, Last name: {ln}, Age: {a}, Address: {adr}, Phone number: {pn}"
    print(name)
    record.append(name)
    if len(record) >= 5:
        print("You cannot add any more entries, consider deleting some")
        return
    question = str(input("Would you like to add another record? (y/n): "))
    if question == "y":
        create()
    if question == "n":
        return
    return ln, name


def read():
    print(*record, sep="\n")

# This is where the user would search by the last name 
def search():
    name = str(input("Enter the last name of the student: "))
    for ln in record:
        if ln in name:
            print(ln)


while ans:
    main()
    ans = str(input("Enter your option [1 - 5]: "))
    if ans == "1":
        create()
    elif ans == "2":
        print("\nShow a record")
        search()
    elif ans == "3":
        print("\nDelete a record")
    elif ans == "4":
        print("\n Displaying all records")
        read()
    elif ans == "5":
        print("\n Goodbye")
        break
else:
    print("\n Not Valid Choice Try again")

讓你的record成為一個字典:

record = {}  # instead of record = []

並按姓氏索引:

record[ln] = name  # instead of record.append(name)

現在您可以通過以下方式進行搜索:

def search():
    ln = input("Enter the last name of the student: ")
    print(record[ln])

暫無
暫無

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

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