我不知道如何将某些值添加到每个键的列表中。我有几个类型(b,m,t,d,c)是键,然后我想把这些项目的成本添加到一个列表中,这个列表就是每次遍历循环时字典的值。 到目前为止,我的情况是:
a={}
allitemcostb=[]
allitemcostm=[]
allitemcostt=[]
allitemcostd=[]
allitemcostc=[]
n=4
while n>0:
itemtype=raw_input("enter the item type-b,m,t,d,c:")
itemcost=input("enter the item cost:")
if itemtype="b":
allitemcostb.append(itemcost)
a[itemtype]=allitemcostb
if itemtype="m":
allitemcostm.append(itemcost)
a[itemtype]=allitemcostm
if itemtype="t":
allitemcostt.append(itemcost)
a[itemtype]=allitemcostt
if itemtype="d":
allitemcostd.append(itemcost)
a[itemtype]=allitemcostd
if itemtype="c":
allitemcostc.append(itemcost)
a[itemtype]=allitemcostc
else:
print "Sorry please enter a valid type"
n=n-1
print a
它不断地给我错误信息,不管是什么东西没有定义,还是语法不正确。 谢谢
试试这个:
给我们一个反馈。如果这能解决你的问题,别忘了标记为已回答。 干杯。你知道吗
与
a[itemtype] = allitemcostb
(简单地将该键的值设置为新成本)不同,如果该键还不存在,则需要创建一个list
,如果该键存在,则需要将其添加到现有的list
。使用setdefault()
方法执行此操作。你知道吗下面只使用了一个带有
itemtype:[itemcost, itemcost...]
的字典,没有单独的list
,省去了手动递增的while
循环,取而代之的是带有xrange
的for
循环,并用更直接的结构替换了大的分支结构(而不是“if it'sa
,doa
”,而是“do what it is”)。行if itemtype in ('b', 'm', 't', 'd', 'c'):
检查输入的itemtype
是否是表示可用选项的单个字符串。如果输入的itemcost
无法转换为float
,则会捕获错误并提示用户重试。你知道吗这里有两个解决方案。你知道吗
第一个不是那么严格。它将允许用户为itemtype输入任何值,但不允许为itemcost输入任何值
第二个表单对用户输入都是严格的,并且会一直提示,直到用户输入期望值
相关问题 更多 >
编程相关推荐