Python:在一个列表中添加一个条目,它是字典中的一个值

2024-10-03 21:35:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我不知道如何将某些值添加到每个键的列表中。我有几个类型(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

它不断地给我错误信息,不管是什么东西没有定义,还是语法不正确。 谢谢


Tags: the列表inputiftypeitementerappend
3条回答

试试这个:

a = {}
all_item_cost_b=[]
all_item_cost_m=[]
all_item_cost_t=[]
all_item_cost_d=[]
all_item_cost_c=[]
n = 4

while n > 0:
    item_type = input("enter the item type-b,m,t,d,c:")
    item_cost = input("enter the item cost:")
    if item_type == "b":
        all_item_cost_b.append(item_cost)
        a[item_type] = all_item_cost_b
    elif item_type == "m":
        all_item_cost_m.append(item_cost)
        a[item_type] = all_item_cost_m
    elif item_type == "t":
        all_item_cost_t.append(item_cost)
        a[item_type] = all_item_cost_t
    elif item_type == "d":
        all_item_cost_d.append(item_cost)
        a[item_type] = all_item_cost_d
    elif item_type == "c":
        all_item_cost_c.append(item_cost)
        a[item_type] = all_item_cost_c
    else:
        print("Sorry please enter a valid type")
    n = n - 1
print(a)

给我们一个反馈。如果这能解决你的问题,别忘了标记为已回答。 干杯。你知道吗

a[itemtype] = allitemcostb(简单地将该键的值设置为新成本)不同,如果该键还不存在,则需要创建一个list,如果该键存在,则需要将其添加到现有的list。使用setdefault()方法执行此操作。你知道吗

下面只使用了一个带有itemtype:[itemcost, itemcost...]的字典,没有单独的list,省去了手动递增的while循环,取而代之的是带有xrangefor循环,并用更直接的结构替换了大的分支结构(而不是“if it's a,do a”,而是“do what it is”)。行if itemtype in ('b', 'm', 't', 'd', 'c'):检查输入的itemtype是否是表示可用选项的单个字符串。如果输入的itemcost无法转换为float,则会捕获错误并提示用户重试。你知道吗

a={}
n=4

for i in xrange(n):
    itemtype = raw_input("enter the item type-b,m,t,d,c:")
    itemcost = raw_input("enter the item cost:")
    try:
        itemcost = float(itemcost)
    except ValueError:
        print "Sorry, please enter a valid cost."
        break
    if itemtype in ('b', 'm', 't', 'd', 'c'):
        a.setdefault(itemtype, []).append(itemcost)
    else:
        print "Sorry, please enter a valid type."

print a

这里有两个解决方案。你知道吗

第一个不是那么严格。它将允许用户为itemtype输入任何值,但不允许为itemcost输入任何值

a={}
n=4

while (n>0):
    itemtype = input("enter the item type-b,m,t,d,c:")
    itemcost = input("enter the item cost:")

    while(True):
        try:
            itemcost = float(itemcost)
            break;
        except ValueError:
            print ("Sorry, please enter a valid cost.")
            itemcost = input("enter the item cost:")

    if itemtype.lower() in "b m t d c".split():
        a[itemtype] = a.get(itemtype,list())+[itemcost]

    n-=1

print (a)

第二个表单对用户输入都是严格的,并且会一直提示,直到用户输入期望值

a={}
n=4

while (n>0):
    itemtype = input("enter the item type-b,m,t,d,c:")
    ##user enters a wrong value
    while(itemtype.lower() not in "b m t d c".split() ):
        print ("Sorry, please enter a valid item.")
        itemtype = input("enter the item type-b,m,t,d,c:")

    itemcost = input("enter the item cost:")
    ##user enters a wrong value
    while(True):
        try:
            itemcost = float(itemcost)
            break;
        except ValueError:
            print ("Sorry, please enter a valid cost.")
            itemcost = input("enter the item cost:")

    a[itemtype] = a.get(itemtype,list())+[itemcost]

    n-=1

print (a)

相关问题 更多 >