python - 在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])
解决方案
您可以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]]
推荐阅读
- azure-application-insights - 将 App Insights 可用性测试部署到英国南部,但奇怪的是 ARM 说俄罗斯
- javascript - 如何在触摸屏上滚动过去的图像时添加悬停效果(无需单击图像只是滑过它们)
- reactjs - Microsoft Edge 中的 Reactjs 路由
- c# - 如何使用带有拦截器的中间件?
- php - Codeigniter 文件上传许可仅适用于图像而不适用于其他人
- python - 每个时期都有不同的数据增强参数
- unity3d - 改变曝光不会统一改变物体上的照明
- python - 无法使用 txt 文件中的数据执行 if 语句
- python - 如何在 / 处修复 FieldError?
- ionic-framework - 从最近的应用程序中清除后,是否可以让应用程序在后台运行?