我正在尝试创建一个购物清单,在您按1时向您显示包含购物清单的文件,当您按2时添加一个新商品,按3时删除一个商品,并在按4时退出。我不知道该为#3做些什么。
老实说,我什至不知道如何开始。
elif (number == 3):
delete_item = input('What item would you like to delete?')
应该从文件中删除用户不需要的内容。
答案 0 :(得分:1)
这是一个示例,如果您想使用JSON格式将购物清单存储在文件中。我提供了一个用于编写,阅读和删除/覆盖的示例。
import json
shopping_list = ["bread", "apple", "carrot"]
# Writing
with open('shopping.txt', 'w') as fh:
json.dump(shopping_list, fh)
# Reading
with open('shopping.txt', 'r') as fh:
shopping_list = json.load(fh)
# Deleting and rewriting
try:
# Here we remove an entry "apple" from the shopping list
shopping_list.remove("apple")
except ValueError:
# In the case that the entry does not exist, do not error
pass
with open('shopping.txt', 'w') as fh:
json.dump(shopping_list, fh)
答案 1 :(得分:1)
以下程序应该可以完成您想要的工作。
由于未指定搜索方法,选项3扫描整个数组并删除由value
指定的项目。
import os
shopping_list = ['foo', 'foo1', 'foo2']
def main():
action = input("Please select an action: 1-4: ")
if action == "1":
print(os.path.dirname(os.path.realpath(__file__)))
elif action == "2":
item_to_add = input("Please type what you want to add: ")
shopping_list.append(item_to_add)
print(shopping_list)
elif action == "3":
item_to_delete = input("Please type exactly what you want to delete: ")
for curr in shopping_list:
if curr == item_to_delete:
shopping_list.remove(curr)
print(shopping_list)
elif action == "4":
print ("Exiting")
exit
else:
print("You did not enter 1-4")
main()
答案 2 :(得分:0)
如果x是要从列表中删除的元素的名称,而shopping_list是列表,则可以这样使用列表理解:
shopping_list = [y for y in shopping_list if y!=x]