Sss123057057 发表于 2021-2-19 18:40:15

字典

书上的
allguess={'1':{'apples':5,'pretzeles':12},
         '2':{'ham sandwiches':3,'apples':2},
         '3':{'cups':3,'apple pies':1}}
def a(guests,item):
    numbrount=0
    for k,v in guests.items():
      numbrount=numbrount+v.get(item,0)
    return numbrount
print('number of things being brought:')
print('apples '+str(a(allguess, 'apples')))
print('cups '+str(a(allguess, 'cups')))
print('cakes '+str(a(allguess, 'cakes')))
print('ham sandwich '+str(a(allguess, 'ham sandwiches')))
print('apple pies '+str(a(allguess, 'apple pies')))
        可是没有用到k,我改成了这样
allguess={'1':{'apples':5,'pretzeles':12},
         '2':{'ham sandwiches':3,'apples':2},
         '3':{'cups':3,'apple pies':1}}
def a(guests,item):
    numbrount=0
    for v in guests.values():
      numbrount=numbrount+v.get(item,0)
    return numbrount
print('number of things being brought:')
print('apples '+str(a(allguess, 'apples')))
print('cups '+str(a(allguess, 'cups')))
print('cakes '+str(a(allguess, 'cakes')))
print('ham sandwich '+str(a(allguess, 'ham sandwiches')))
print('apple pies '+str(a(allguess, 'apple pies')))
有什么弊端吗?

kogawananari 发表于 2021-2-20 01:25:59

没有

_2_ 发表于 2021-2-20 05:22:23

那除了这样,难道还有别的更加简便的把字典的键和值单独提取出来的方法吗?{:10_256:}
页: [1]
查看完整版本: 字典