我有一个代表库存项目及其值(value)的类:
class stock:
def __init__(self, stockName, stockType, value):
self.name = stockName
self.type = stockType
self.value = value
我有大量库存,所以我制作了一个库存对象列表,从中我可以访问单个项目的值,例如 stockList[12].value
我想将所有库存商品的值(value)相加,即“衬衫”。以下工作正常:
shirtValue = sum([s.value for s in stockList if s.value == 'shirt'])
好的,好的。但现在我有一个 stockType
列表,并希望对与 stockType 列表中特定条目匹配的项目的值(value)求和,例如:
stockTypeValue[0] = sum([s.value for s in stockList if s.value == stockType[0]])
where stockType[0] = 'shirt'
这不起作用。我知道为什么 - 这是因为在 Python 3 中列表推导式有它们自己的范围(参见此处的详细答案:Accessing class variables from a list comprehension in the class definition)
我的问题是: 我编写的代码(我认为它可以在 Python 2 中运行)看起来很棒、干净、易于理解,并且对于未经训练的人来说看起来非常 pythonic。
但我不知道如何在 Python 3 中以一种漂亮的 Pythonic 方式做同样的事情。我要回到大循环结构。
在 Python 3 中执行此操作的最佳方法是什么?
* 编辑 * 错误信息:
这是我正在尝试做的一个例子:
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'])
输出:
Out[5]: 53.3
但如果我将“衬衫”放入变量中:
stockType = 'shirt'
sum([s.value for s in stockList if s.type==stockType])
输出:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "<console>", line 1, in <listcomp>
NameError: name 'stockType' is not defined
最佳答案
This doesn't work. I know Why - it is because in Python 3 list comprehensions have their own scope (See detailed answer here: Accessing class variables from a list comprehension in the class definition )
事实并非如此。我的意思是,当然那个问题的答案是正确的,但这不是这里发生的事情。该问题仅与定义时类主体中发生的表达式相关。如果你是但是在一个方法中就完全没有问题了。
但是,可能会失败(“可能”因为您没有提供错误消息)是因为目标列表 stockTypeValue
未初始化。
>>> stockTypeValue[0] = 'something'
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
stockTypeValue[0] = 'something'
NameError: name 'stockTypeValue' is not defined
所以我们现在可以定义它并分配一个空列表;但列表仍然是空的:
>>> stockTypeValue = []
>>> stockTypeValue[0] = 'something'
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
stockTypeValue[0] = 'something'
IndexError: list assignment index out of range
相反,您必须将结果附加到空列表中:
>>> stockTypeValue.append('something')
>>> stockTypeValue[0]
'something'
重放您的示例:
>>> 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'])
53.2
>>> stockType = 'shirt'
>>> sum([s.value for s in stockList if s.type == stockType])
53.2
关于Python 3、列表理解、作用域以及如何与外部变量进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29296912/