Python购物清单文本应用程序,节省问题

时间:2017-01-06 22:23:41

标签: python list save shopping

我正在尝试学习python,作为一个项目,我开始制作购物清单文本脚本。该脚本应该询问您是否要在列表中添加/删除项目。它还具有打印列表的功能。您可以将列表另存为.txt文档,并在需要时继续。

我的第一个问题是,当我保存列表项并将它们带回来时,所有不同的列表项都成为一个列表项。所以我可以添加,但我无法从列表中删除单个项目。

我现在尝试从.txt文档中拆分列表。我认为这会拆分列表,但现在每次启动脚本时都会添加额外的符号保存,然后重新启动它。我可以做一些小的调整,还是我的想法可以实现里程数?

#I think the main problem is in the program_start_list_update_from_file defenition

# Shopping list simulator
shoppingList = []

def program_start_list_update_from_file():
    global shoppingList
    outputname = "shoppinglistfile.txt"
    myfile = open(outputname, 'r')
    lines = str(myfile.read().split(', '))
    shoppingList = [lines]
    myfile.close()

def shopping_list_sim():
    print("Would you like to add (a) delete (d) or list (l) items in your shopping list?")
    print('Press (e) for exit and (s) for list saving')
    playerInput = input()
    outputname = "shoppinglistfile.txt"


    try:
        if playerInput == "a":
            print("What item would you like to add?")
            shoppingList.append(input())
            print("Item added")
            shopping_list_sim()


        elif playerInput == "d":
            print("What item would you like to remove?")
            print(shoppingList)
            shoppingList.remove(input())
            print("Item removed")
            shopping_list_sim()

        elif playerInput == "l":
            myfile = open(outputname, 'r')
            yourResult = ', '.join(myfile)
            print(yourResult)
            shopping_list_sim()


        elif playerInput == "e":
            print("Exiting program")
            sys.exit()

        elif playerInput == "s":
            myfile = open(outputname, 'w')
            myfile.write(', '.join(shoppingList))
            myfile.close()
            shopping_list_sim()
        else:
            print("Please use the valid key")
            shopping_list_sim()
    except ValueError:
        print("Please put in a valid list item")
        shopping_list_sim()

program_start_list_update_from_file()
shopping_list_sim()

1 个答案:

答案 0 :(得分:1)

问题的根源是

lines = str(myfile.read().split(', '))
shoppingList = [lines]

您将文件拆分为一个列表,从该列表中删除一个字符串,然后将该单个字符串添加到列表中。

shoppingList = myfile.read().split(', ')

足以做你想做的事:split为你创建一个列表。

您应该考虑从递归调用切换到循环: 每次递归调用都会在构建新stack frame时增加开销,在这种情况下完全没必要。

你现在拥有它,每个新提示都有一个新的堆栈框架:

shopping_list_sim()
    shopping_list_sim()
        shopping_list_sim()
            shopping_list_sim()
                ...

如果在循环中执行此操作,则不会递归构建堆栈。