Python-允许用户修改列表中的项目名称,然后用新名称显示列表?

Python-允许用户修改列表中的项目名称,然后用新名称显示列表?,python,edit,Python,Edit,这部分程序的代码如下所示。我试图允许用户编辑其中一个项目的名称,然后当他在程序中输入show命令时,更新的名称就会出现在那里。我一直想知道使用什么函数允许用户编辑名称。谢谢 def edit(item_list): number = int(input("Number: ")) list.insert(item) item = input("Updated name: ") print(item +"was updated") def main(): # thi

这部分程序的代码如下所示。我试图允许用户编辑其中一个项目的名称,然后当他在程序中输入show命令时,更新的名称就会出现在那里。我一直想知道使用什么函数允许用户编辑名称。谢谢

def edit(item_list):
   number = int(input("Number: "))
   list.insert(item)
   item = input("Updated name: ")
   print(item +"was updated")

def main():
    # this is the item list
    item_list = ["wooden staff","wizard hat","cloth shoes"]  

因此,如果我输入edit作为命令,然后为第一项写入hello,我希望它用hello替换WoodStaff。

您只需重新指定索引即可修改列表项:

def edit(item_list):
    number = int(input("Number: "))
    curr_item = item_list[number]
    new_item = input("Updated name: ")
    item_list[number] = new_item
    print("{} was updated to {}".format(curr_item, new_item))
    return item_list

item_list = edit(item_list)
我假设您的
print
语句是为了表明发生了什么变化。如果您只想重新打印用户输入的内容,可以对其进行更改。

您可以尝试:

def edit(item_list):
    pos = int(input("Number: "))    
    new_value = input("Updated name: ")
    item_list[pos-1] = new_value
    print"%s was updated" % (new_value)

我希望这对您有所帮助

您不能使用
insert
,因为它完全符合其英文定义。它会向列表中添加一个新项目,但不会替换列表中的某些内容。
item\u list
不是全局变量。除非调用了
edit()
,并且
返回了一些东西,否则这是如何工作的?这是编写代码的最简单方法吗?谢谢@tejashpatel否,因为它不起作用,在您的示例中,为返回编辑。我并没有试图修复他的整个脚本,因为其他原因,例如无法调用
edit
,所以目前也无法修复。我只是试图修复
编辑
功能,以便它实际更新发送给它的列表。我已经删除了我的否决票,因为你正确地解决了我的问题,但我确实认为,从示例代码中可以看出,这并不是为了给出完整的答案(异常处理我认为是不同的,但至少预期的流与预期的输入…)假设我输入了
0
。然后会发生什么?我假设输入是一个大于0的整数。感谢您的输入!当用户输入一个无效的数字进行编辑时,我如何在其中放置一个显示无效消息的命令?@jorgelbertoruedaflores