两个字典(价格、库存)的值相乘然后求和

2024-05-20 08:36:45 发布

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

我需要将每个键的值相乘,然后将所有值相加以打印单个数字。我知道这可能很简单,但我被卡住了

在我看来,我会用这样的方式来解决这个问题:

for v in prices:
total = sum(v * (v in stock))
print total

但这样的事情是行不通的:)

prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3 }

stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15 }

Tags: inappleforstock方式数字事情total
3条回答

如果你知道如何遍历字典,如何用键索引字典,如何理解字典,那将是一个直截了当的过程

>>> total = {key: price * stock[key] for key, price in prices.items()}
>>> total
{'orange': 48.0, 'pear': 45, 'banana': 24, 'apple': 0}

即使Python的实现不提供字典理解(<;Py 2.7),也可以将其作为列表理解传递给内置的dict

>>> dict((key, price * stock[key]) for key, price in prices.items())
{'orange': 48.0, 'pear': 45, 'banana': 24, 'apple': 0}

如果不想在2.X和3.X之间兼容,也可以使用iteritems而不是 项目

{key: price * stock[key] for key, price in prices.iteritems()}

如果您只需要一个结果的总和,可以将各个产品传递给sum

>>> sum(price * stock[key] for key, price in prices.items())
117.0

根据任务描述,代码学院的正确答案:

 prices = {
       "banana" : 4,
       "apple"  : 2,
       "orange" : 1.5,
       "pear"   : 3,
   }
   stock = {
        "banana" : 6,
        "apple"  : 0,
        "orange" : 32,
        "pear"   : 15,
    }

    for key in prices:
        print key
        print "price: %s" % prices[key]
        print "stock: %s" % stock[key]

     total = 0
     for key in prices:
        value = prices[key] * stock[key]
        print value
        total = total + value
    print total   

如果你想让这些人:

>>> {k: prices[k]*stock[k] for k in prices}
{'orange': 48.0, 'pear': 45, 'banana': 24, 'apple': 0}

或者直接计算总数:

>>> sum(prices[k]*stock[k] for k in prices)
117.0

相关问题 更多 >