Python 从二维列表中获取元素并根据用户输入进行更改

Python fetching element from 2d list and changing based on user input

我是编程新手,很抱歉这是一个常见问题。我正在尝试更改二维列表中的第一个 name/last 名称等元素,用户输入用户名,如果用户名 returns 为真,则要求用户 select 一个选项他们想更改的名字或姓氏。我的代码只更改二维列表中第一个列表的名字或姓氏。有谁知道如何根据列表中某个元素的用户 selection 专门针对列表元素?任何帮助将不胜感激:)。

allUserDetails = [["John", "Doe", "User", "Sales", "johndoe91", "password"],
                  ["James", "Hill", "Admin", "Administrator", "hill95", "12345678"]]


def update_user():
    print("\n:: Update User ::")
    print("-" * 25)
    print("\nWhich field would you like to update?\n")
    print("1. First Name")
    print("2. Last Name")


print(allUserDetails)
searchUser = input("\nInput username to edit (press 1 to return to Main Menu): ").lower()

while searchUser != "1":
    for x in allUserDetails:
        if x[4] == searchUser:
            print()
            print(searchUser, "found in the list")
            update_user()
            updateSelection = input("\nInput number of field or press Q/q to return to Menu 3: ")
            if updateSelection == "1":
                newFirstName = input("Input new First Name: ")
                allUserDetails[0][0] = newFirstName
                print(allUserDetails)
            if updateSelection == "2":
                newLastName = input("Input new Last Name: ")
                allUserDetails[0][1] = newLastName
                print(allUserDetails)
            if updateSelection == ("Q", "q"):
                searchUser = input("\nInput username to edit (press 1 to return to Main Menu): ").lower()

    for x in allUserDetails:
        if x[4] != searchUser:
            # Print not found message
            print()
            print(searchUser, "not found")
            continue
    else:
        break
    

您的问题来自列表的索引: allUserDetails[0][0] = newFirstName

这将始终更新第一个索引。但是,您正在尝试更新列表 x: x[0] = newFirstName

同样的问题也适用于 newLastName