我有一个代表库存物品及其价值的类:
class stock:
def __init__(self, stockName, stockType, value):
self.name = stockName
self.type = stockType
self.value = value
我有大量库存,因此我列出了库存对象列表,我可以从中访问单个项目的价值,例如stockList[12].value
我想将所有“衬衫”库存商品的价值相加。以下工作正常:
shirtValue = sum([s.value for s in stockList if s.value == 'shirt'])
好的。但现在我有一个清单stockType
并希望对与 stockType 列表中的特定条目匹配的项目的值进行求和,例如:
stockTypeValue[0] = sum([s.value for s in stockList if s.value == stockType[0]])
where stockType[0] = 'shirt'
这是行不通的。我知道为什么 - 这是因为在 Python 3 中列表推导式有自己的作用域(请参阅此处的详细答案:从类定义中的列表理解访问类变量 https://stackoverflow.com/questions/13905741/accessing-class-variables-from-a-list-comprehension-in-the-class-definition )
我的问题是这样的:我编写的代码(我认为可以在 Python 2 中运行)看起来很棒,它干净、易于理解,并且对于未经训练的人来说看起来非常 Pythonic。
但我不知道如何在 Python 3 中以一种很好的 Python 方式做同样的事情。我将回到大循环结构。
在 Python 3 中执行此操作的最佳方法是什么?
* Edit *错误信息:
这是我正在尝试做的事情的一个例子:
stockList=[]
stockList.append(stock('product A', 'shirt', 53.2))
stockList.append(stock('product B', 'hat', 20.2))
sum([s.value for s in stockList if s.type=='shirt'])
output:
Out[5]: 53.3
但如果我将“衬衫”放入变量中:
stockType = 'shirt'
sum([s.value for s in stockList if s.type==stockType])
output:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "<console>", line 1, in <listcomp>
NameError: name 'stockType' is not defined