第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

對字典中的總值求和的函數(shù)

對字典中的總值求和的函數(shù)

有只小跳蛙 2021-09-01 10:26:01
我有一個包含多個條目的 dict 值。   inventory = {847502: ['APPLES 1LB', 2, 50], 847283: ['OLIVE OIL', 1, 100], 839529: ['TOMATOS 1LB', 4, 25],                  483946: ['MILK 1/2G', 2, 50], 493402: ['FLOUR 5LB', 2, 50], 485034: ['BELL PEPPERS 1LB', 3, 50]}我想創(chuàng)建一個函數(shù)來獲取價值項目的總數(shù),即。sum((2*50)+ (1*100) etc...) 我想我快到了,但這似乎只添加了第一個值....def total_and_number(dict):    for values in dict.values():        #print(values[1]*values[2])        total =0        total += (values[1]* values[2])        return(total)total_and_number(inventory)
查看完整描述

3 回答

?
一只名叫tom的貓

TA貢獻(xiàn)1906條經(jīng)驗 獲得超3個贊

Return 和 total 行錯位。這將返回 650。


inventory = {847502: ['APPLES 1LB', 2, 50],

             847283: ['OLIVE OIL', 1, 100], 839529: ['TOMATOS 1LB', 4, 25], 

             483946: ['MILK 1/2G', 2, 50], 493402: ['FLOUR 5LB', 2, 50],

             485034: ['BELL PEPPERS 1LB', 3, 50]

}


def total_and_number(dict):

    total = 0

    for values in dict.values():

        total += values[1]*values[2]

    return(total)


total_and_number(inventory)


查看完整回答
反對 回復(fù) 2021-09-01
?
守候你守候我

TA貢獻(xiàn)1802條經(jīng)驗 獲得超10個贊

看起來每個值都是一個列表(盡管它可能應(yīng)該是一個元組):

itemname, qty, eachprice

所以它應(yīng)該很容易迭代并直接求和:

sum(qty*eachprice for _, qty, eachprice in inventory.values())


查看完整回答
反對 回復(fù) 2021-09-01
?
守著星空守著你

TA貢獻(xiàn)1799條經(jīng)驗 獲得超8個贊

用:


def total_and_number(d):

    tot = 0

    for k, v in d.items():

        tot += v[1]*v[2]

    return tot


total_and_number(inventory)


查看完整回答
反對 回復(fù) 2021-09-01
  • 3 回答
  • 0 關(guān)注
  • 211 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號