【问题标题】:How do I find the total (Python) [closed]我如何找到总数(Python)[关闭]
【发布时间】:2013-12-14 07:37:00
【问题描述】:

我想遍历这些字典,看看如果我在stock 中卖掉所有东西,我能赚多少钱。这意味着我必须将 prices 中的项目乘以 stock 中的项目并添加我得到的产品。如何使用 for 循环做到这一点?

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

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

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

【问题讨论】:

    标签: python loops for-loop dictionary


    【解决方案1】:

    你需要遍历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)
    

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

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

    【讨论】:

    • 1.如果prices中的键不是库存2中键的超集,它将失败。你可以简单地说for x in stock,它会很有效
    • @thefourtheye +1 两点,尤其是第二点。
    • 这不是解决这个问题的一种非常有效的方法。请在thefourthey's answer上查看我的cmets。
    • @SimonC 是的,我明白你的意思。我已经更新了我的答案,感谢您的帮助!
    • @aga get 方法有什么作用,iteritems 是什么?
    【解决方案2】:

    以上答案很好,但可能不适合初学者。这里有一段更长一点、速度稍慢的代码,可以帮助你理解......

    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
    

    【讨论】:

    • 请不要在实践中这样做。例外是针对特殊情况。您可以检查密钥是否存在,而无需依赖抛出的异常。
    • @adsmith 谢谢!我发现你的答案更容易理解。
    【解决方案3】:

    您可以使用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
    

    【讨论】:

    • 还是print sum(v * prices.get(k,0) for k, v in stock.iteritems())
    • @SimonC 如果价格中的键不是库存键的超集,它将失败。
    • 如果密钥不存在,使用第二个参数调用get 将返回第二个参数。这避免了额外的字典查找。 iteritems 函数避免创建所有键值对的列表。
    • @SimonC 是的,我得到了get 部分,但这是不必要的。我拿了iteritems点:)
    • 为什么说没必要?您目前正在为stock 中的每个键进行两次字典查找。更改为 get 会将其减少为每个键一次字典查找。
    【解决方案4】:

    有点接近生产使用。

    #!/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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-07
      • 1970-01-01
      • 2019-03-21
      • 2022-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多