因此,我正在寻找一种方式,以单独的字典形式添加单独的项目清单,其中包含杂货店项目的名称,价格和数量。我几周前才开始编程,所以请原谅我可怕的代码和初学者的错误。
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)当我输入两个项目(即垃圾邮件和鸡蛋)的信息时,我得到以下输出:
[{'name': 'Eggs', 'quantity': 12, 'cost': 1.5}, {'name': 'Eggs', 'quantity':
12, 'cost': 1.5}]输出没有创建两个不同的项,而是重复我输入的最近一个项。我犯了一些基本的语义错误,我不知道如何从用户输入循环中用不同的项填充"grocery_history“列表。我试着用pythontutor.com寻求帮助,但只是因为愚蠢而被斥责。任何帮助都是非常感谢的。
发布于 2018-04-06 00:50:49
尝试这样做:
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)通过在每个循环中创建一个新字典,您将避免所看到的重复错误。
发布于 2018-04-06 00:55:12
您应该将current_item字典移到while中,例如:
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尽快停止循环,而不需要再次检查条件发布于 2018-04-06 01:00:09
这是因为Python中的字典是可变的对象:这意味着您实际上可以修改它们的字段,而无需创建一个全新的字段。
如果您想更深入地理解可变对象和不可变对象之间的主要区别,请遵循这个链接。
这是您的代码略有修改,并工作:
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)https://stackoverflow.com/questions/49683609
复制相似问题