我有一本字典,其中包含如下列表: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] 中每个项目的总和)
1 回答
![?](http://img1.sycdn.imooc.com/5458506b0001de5502200220-100-100.jpg)
拉莫斯之舞
TA贡献1820条经验 获得超10个赞
是的:迭代值本身,从每个值中提取出所需的产品。将该结果sum
直接作为生成器提供。
sum(entry[2] * entry[3] for entry in a.values())
添加回答
举报
0/150
提交
取消