【发布时间】:2018-04-16 04:29:26
【问题描述】:
我尝试阅读了许多类似的问题(这似乎最接近:Python sum dict values based on keys),但仍然难以回答以下问题。归结为基础
我有以下 3 个以列表为键的字典:
{'milk': ['gallons', 5, 10, 50]}
{'eggs': ['cartons', 5, 2, 10]}
{'bacon': ['packages', 5, 7, 35]}
我希望能够对每个嵌套列表的最后一个值求和,并将95 的预期的单个值打印到屏幕上。
我已经看到了涉及 lambda 的类似问题的答案,但我知道必须有一种方法可以通过迭代列表来做到这一点。我见过 sum 和 Counter 的用法,我愿意接受任何解释。 提前谢谢你。
更新/添加上下文
感谢那些已经做出回应的人。我意识到可能需要更多的上下文来回答这个问题。
这些条目是从这个类中生成的:
class GroceryCart(dict):
def __init__(self):
self = {}
def addToCart(self, item, units, quantity, price):
item_total = quantity*price
self.update({item:[units, quantity, price, item_total]})
def returnCart(self):
return self
my_cart = GroceryCart()
这就是你获得时髦信息结构的地方。
我在下面尝试了@ggorlan 的回复,但得到了关于没有使用 str 值的回溯错误.values()
Traceback (most recent call last):
File "grocery_store.py", line 156, in <module>
total = sum(sum(y[-1] for y in x.values()) for x in my_cart)
File "grocery_store.py", line 156, in <genexpr>
total = sum(sum(y[-1] for y in x.values()) for x in my_cart)
AttributeError: 'str' object has no attribute 'values'
【问题讨论】:
-
列表不能是字典中的键。列表只能是值(如您在示例中所使用的)。另外,这三个字典是否在一个更大的数据结构中?
-
到目前为止你有什么尝试?
-
如果你的字典是 a 那么 sum([a[k][3] for k in a]) 将打印 95,但你必须将 a 写成 {'bacon': ['packages' , 5, 7, 35], 'eggs': ['cartons', 5, 2, 10], 'milk': ['gallons', 5, 10, 50]}
-
我尝试过调整 this list comprehension and loop example 和 this post 之类的东西,尝试尝试使用该解决方案,看看它是否可以应用于我的场景。 Tbh 一直在尝试系统地深入研究以找出如何调用列表的最后一个值。但如果我能做到这一点,我会将其存储在一个新列表中以在迭代后求和吗?
-
我认为您需要退后一步,以更广泛的方式告诉我们您正在尝试做什么。这似乎是一种错误的数据管理方式。
标签: python list dictionary sum