猿问

获取字典中每个列表中 2 个位置值的乘积之和

我有一本字典,其中包含如下列表:


a = {'Dairy-Milk': ['Dairy-Milk', '12345', '800', 1], 'test': ['test', '1111', '600', 1]}

我想遍历字典,对 (each_dictionary_Item[2] *each_dictionary_Item[3]) 执行乘法,然后获取所有项目的总和。


据我所知,我调用了 a.get_keys 然后我遍历了键中的每个项目,并调用了 list pos 2 * 3,然后将其附加到另一个列表中,在其中我使用 sum(列表)....当添加新项目时,这会给我错误的总和。


 for item in self.listofKeys:

            thequantity = self.productList[item][3]

            thecash = self.productList[item][2]

            multiplied = float(thequantity) * float(thecash)

            self.thesumsList.append(multiplied)


        self.ids.thetotal.text = "Total Payable: " + str(sum(self.thesumsList))

有没有更干净的方法来实现我想要的?(获取列表 list[3] * list[3] 中每个项目的总和)


12345678_0001
浏览 84回答 1
1回答

拉莫斯之舞

是的:迭代值本身,从每个值中提取出所需的产品。将该结果sum直接作为生成器提供。sum(entry[2] * entry[3] for entry in a.values())
随时随地看视频慕课网APP

相关分类

Python
我要回答