首页 > 解决方案 > 在python中使用用户输入修改列表

问题描述

我想知道如何获取此用户输入(如下)并仅修改列表中已有的项目。如果用户没有输入与列表中显示的相同的项目,则只需将输入添加为新的杂货项目。

列表

inventory = [['Milk,   3.99,  25'],
             ['Bread,  1.99,  35'],
             ['Eggs,   1.99,  50'],
             ['Flour,  0.52,  20'],
             ['Rice,   0.72,  35']]

输入

modItem = input("Enter the name of an existing item you want to modify:")
modPrice = input("Enter the new price of the item:")
modStock = input("Enter the new stock of the item:")
inventory.append([modItem, modPrice, modStock])

标签: python

解决方案


您可以enumerate在迭代元素时使用和修改列表:

inventory = [['Milk,   3.99,  25'],
             ['Bread,  1.99,  35'],
             ['Eggs,   1.99,  50'],
             ['Flour,  0.52,  20'],
             ['Rice,   0.72,  35']]

modItem = 'Milk' 
modPrice = 4
modStock = 30

found = False
for idx, elt in enumerate(inventory):
    if modItem in elt[0]:
        inventory[idx] = [f"{modItem}, {modPrice}, {modStock}"] # modify the element at the found index
        found = True
        break

if not found:
        inventory.append([f"{modItem}, {modPrice}, {modStock}"])
print(inventory)

输出:

[['Milk, 4, 30'], ['Bread,  1.99,  35'], ['Eggs,   1.99,  50'], ['Flour,  0.52,  20'], ['Rice,   0.72,  35']]

此外,我建议将内部列表保留为元素列表。目前,它只是一个带有str对象的元素。

inventory = [['Milk', 3.99, 25],
             ['Bread', 1.99, 35],
             ['Eggs', 1.99, 50],
             ['Flour', 0.52, 20],
             ['Rice', 0.72, 35]]

found = False
for idx, elt in enumerate(inventory):
    if modItem == elt[0]:
        inventory[idx] = [modItem, modPrice, modStock]
        found = True
        break

if not found:
    inventory.append([modItem, modPrice, modStock])
print(inventory)

输出:

[['Milk', 4, 30], ['Bread', 1.99, 35], ['Eggs', 1.99, 50], ['Flour', 0.52, 20], ['Rice', 0.72, 35]]

推荐阅读