用用户输入替换列表中的项目,无需用户输入索引号

问题描述 投票:0回答:1

我想获取用户的字符串输入来覆盖列表中的项目,而不更改项目的位置,也不需要被覆盖的项目的索引号。

目前,我已经获得了一堆代码来查找用户想要替换的项目,并编写了代码来获取替换字符串,我只是无法弄清楚如何用新输入实际替换该项目。这是我当前的代码:


list = []

while True:
    command = input ("Type add, show, remove, edit or exit: ")
    command = command.strip()
    command = command.capitalize()

    match command:
    case 'Edit' | 'Change':
            action = input("Edit from the To Do list:  ")
            action = action.strip()
            action = action.capitalize()

            if action in list:
                act = input("Editing action " + action + " with: ")
                act = act.strip()
                act = act.capitalize()

                list.append(act)
                print ("Action " + action + " will be replaced with action " + act + ".")
                list.remove(action)

            else:
                print ("Action unidentified. Please try again later.")

我一直无法找到一个工作代码来完成我想要的程序,目前我的代码并不完全是我想要的,因为它删除了该项目,只是将字符串添加到了底部列表。 我仍然认为自己是 python 的初学者,而且我对 PyCharm 还很陌生,所以任何帮助将不胜感激。

python list replace pycharm
1个回答
0
投票

这是用新字符串替换该项目的简单解决方案:

# With the list.index(action), we are getting the index of the input value and 
# then with list[list.index(action)] = act, we are replacing the value into that index position


list[list.index(action)] = act

使用 list.index(action),我们获取输入值的索引,然后使用 list[list.index(action)] = act,我们将值替换到该索引位置

    match command:
        case 'Edit' | 'Change':
                action = input("Edit from the To Do list:  ")
                action = action.strip()
                action = action.capitalize()

                if action in list:
                    act = input("Editing action " + action + " with: ")
                    act = act.strip()
                    act = act.capitalize()

                    list[list.index(action)] = act
                    print(list)
© www.soinside.com 2019 - 2024. All rights reserved.