首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python Grocery列表Python 3音频挑战

Python Grocery列表Python 3音频挑战
EN

Stack Overflow用户
提问于 2018-04-06 00:44:26
回答 3查看 9.1K关注 0票数 1

因此,我正在寻找一种方式,以单独的字典形式添加单独的项目清单,其中包含杂货店项目的名称,价格和数量。我几周前才开始编程,所以请原谅我可怕的代码和初学者的错误。

代码语言:javascript
复制
grocery_item = dict()
current_item = dict()
grocery_history = []
choice = 0
stop = True
while stop == True:
    current_item['name'] = str(input('Item name: '))
    current_item['quantity'] = int(input('Amount purchased: '))
    current_item['cost'] = float(input('Price per item: '))
    grocery_history.append(current_item)
    choice = str(input('Press c to continue or q to quit'))
    if choice == 'c':
        stop = True
    else:
        stop = False
 print(grocery_history)

当我输入两个项目(即垃圾邮件和鸡蛋)的信息时,我得到以下输出:

代码语言:javascript
复制
[{'name': 'Eggs', 'quantity': 12, 'cost': 1.5}, {'name': 'Eggs', 'quantity': 
12, 'cost': 1.5}]

输出没有创建两个不同的项,而是重复我输入的最近一个项。我犯了一些基本的语义错误,我不知道如何从用户输入循环中用不同的项填充"grocery_history“列表。我试着用pythontutor.com寻求帮助,但只是因为愚蠢而被斥责。任何帮助都是非常感谢的。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-04-06 00:50:49

尝试这样做:

代码语言:javascript
复制
grocery_item = dict()
grocery_history = []
choice = 0
stop = True
while stop == True:
    current_item = dict()
    current_item['name'] = str(input('Item name: '))
    current_item['quantity'] = int(input('Amount purchased: '))
    current_item['cost'] = float(input('Price per item: '))
    grocery_history.append(current_item)
    choice = str(input('Press c to continue or q to quit'))
    if choice == 'c':
        stop = True
    else:
        stop = False
print(grocery_history)

通过在每个循环中创建一个新字典,您将避免所看到的重复错误。

票数 0
EN

Stack Overflow用户

发布于 2018-04-06 00:55:12

您应该将current_item字典移到while中,例如:

代码语言:javascript
复制
while True:
    current_item = {}
    # accepts user inputs here
    grocery_history.append(current_item)
    choice = str(input('Press c to continue or q to quit'))
    if choice != 'c':
        break

其他一些注意事项:

  • 不需要在循环之前启动choice = 0
  • 使用break尽快停止循环,而不需要再次检查条件
票数 0
EN

Stack Overflow用户

发布于 2018-04-06 01:00:09

这是因为Python中的字典是可变的对象:这意味着您实际上可以修改它们的字段,而无需创建一个全新的字段。

如果您想更深入地理解可变对象和不可变对象之间的主要区别,请遵循这个链接

这是您的代码略有修改,并工作:

代码语言:javascript
复制
grocery_history = []
while True:
    name = input('Item name: ').strip()
    quantity = int(input('Amount purchased: '))
    cost = float(input('Price per item: '))
    current_item = {'name':name, 'quantity':quantity, 'cost':cost} 
    grocery_history.append(current_item)
    choice = str(input('Press c to continue or q to quit: '))
    if choice == 'q':
        break
print(grocery_history)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49683609

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档