繁体   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