我如何找到总数(Python)

时间:2013-12-14 07:37:00

标签: python loops for-loop dictionary

我想循环浏览这些词典,并发现如果我在stock中出售了所有内容,我会做多少。这意味着我必须将prices中的项目乘以stock中的项目并添加我得到的产品。我如何使用for循环?

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

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

请保持简单的答案,我只是初学者:)

4 个答案:

答案 0 :(得分:2)

您需要遍历stockprices字典的键,获取两个字典的相应值,将它们相乘并得到总和。这正是提供的代码片段所做的:

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

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

print sum(prices[x] * stock[x] for x in stock if x in prices)

更新:如果您使用提供的默认值as SimonC explained通过prices方法从get获取值,则可以减少字典查找次数:

print sum(prices.get(k, 0) * v for k,v in stock.iteritems())

答案 1 :(得分:1)

您可以使用sum功能获取总数。

print sum(v * prices[k] for k, v in stock.iteritems() if k in prices)

上述陈述可以写成

total = 0
for k, v in stock.items():
    if k in prices:
        total += v * prices[k]
print total

答案 2 :(得分:1)

以上答案很棒,但也许不适合初学者。这是一段稍微慢一点的代码,可以帮助你理解......

amount = 0 # Used to increment your inv value
for eachKey in stock:
# Iterate through your stock, pulling values for each item you have
    try:
        amount += stock[eachKey]*prices[eachKey]
        # Try to add your total inventory price for the current iteration
        # to your total, but if that item in your stock has no price set...
    except KeyError as e:
        print("Your item {} has no price!".format(eachKey))
        # Let you know that there's no price for this item
print("Your total inventory has value ${:.2f}".format(amount))
# Print out your total inventory value

答案 3 :(得分:-1)

稍微接近生产用途。

#!/usr/bin/env python2.7


import types
from pprint import pprint as prn


class Store (object):

    def __init__ (self):
        self.__stock = {}

    @property
    def stock (self):
        return self.__stock

    @stock.setter
    def stock (self, products):
        """
        Args:
            products: {'<title>': [<quantity>, <price>[,
                       <...>}
        """
        if isinstance(products, dict):
            self.__stock.update(products)
        else:
            raise ValueError

    def income (self):
        stk = self.__stock
        return sum((stk[t][0]*stk[t][1] for t in stk))

    def __update (self, title, id, value):
        if title in self.__stock:
            self.__stock[title][id] = float(value)
        else:
            raise ValueError

    def update_quantity (self, title, q):
        self.__update(title, 0, q)

    def update_price (self, title, p):
        self.__update(title, 1, p)

    def remove (self, title):
        self.__stock.pop(title)


if '__main__' == __name__:
    st = Store()
    st.stock = {'banana': (6, 4)} # adding the new product

    # adding a group of new products
    st.stock = {'apple': [0, 2],
                'orange': [32, 1.5],
                'pear': [15, 3]}

    prn(st.stock)
    prn(st.income()) # calculating income

    st.update_quantity('apple', 1) # updating quantity for apples
    prn(st.stock)
    prn(st.income())

    st.remove('pear') # < removing pears
    st.stock = {'grape': [10, 2.5]}
    st.update_price('orange', 4.5) # updating price
    prn(st.stock)
    prn(st.income())


# >>> {'apple': [0, 2], 'banana': (6, 4), 'orange': [32, 1.5], 'pear': [15, 3]}
# >>> 117.0
# >>> {'apple': [1.0, 2], 'banana': (6, 4), 'orange': [32, 1.5], 'pear': [15, 3]}
# >>> 119.0
# >>> {'apple': [1.0, 2], 'banana': (6, 4), 'grape': [10, 2.5], 'orange': [32, 4.5]}
# >>> 195.0