Python- 允许用户修改列表中的项目名称,然后以新名称显示列表?
Python- Allow user to modify item name in list and then show list with new name?
这部分程序的代码如下。我试图让用户编辑其中一项的名称,然后当他在程序中输入 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 作为我的命令,然后我为第 1 项写了 hello,我希望它用 hello 替换 wooden staff。
您可以通过简单地重新分配该索引来修改列表项:
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)
希望对你有所帮助
这部分程序的代码如下。我试图让用户编辑其中一项的名称,然后当他在程序中输入 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 作为我的命令,然后我为第 1 项写了 hello,我希望它用 hello 替换 wooden staff。
您可以通过简单地重新分配该索引来修改列表项:
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)
希望对你有所帮助