Python 类属性中的Lambda函数
任务:在Python 类属性中的Lambda函数,python,class,lambda,syntax-error,Python,Class,Lambda,Syntax Error,任务:在self.priceTable中获取price,输入给定的reqId 类方法的此代码按预期工作: priceTable = self.priceTable price = next(filter(lambda priceTable: priceTable['reqId'] == reqId, priceTable), None) 此代码给出了无效的语法错误: price = next(filter(lambda self.priceTable: self.priceTable['req
self.priceTable
中获取price
,输入给定的reqId
类方法的此代码按预期工作:
priceTable = self.priceTable
price = next(filter(lambda priceTable: priceTable['reqId'] == reqId, priceTable), None)
此代码给出了无效的语法错误:
price = next(filter(lambda self.priceTable: self.priceTable['reqId'] == reqId, self.priceTable), None)
怎么了?有其他建议吗
self.priceTable
不是有效的参数名称。参数应该只是名称,您可以将self.priceTable
作为参数传递给lambda函数:
price = next(filter(lambda priceTable: priceTable['reqId'] == reqId, self.priceTable), None)
lambda
后面必须跟一个普通变量,就像函数的参数一样。您只需在过滤器的参数中提供self.priceTable
:
price = next(filter(lambda p: p['reqId'] == reqId, self.priceTable), None)
您的问题不清楚,因为其中的代码太少,无法真正理解您试图实现的目标。如果这不适用,非常抱歉。但是,从目前的情况来看,我认为您根本不需要使用lambda
或内置的filter
功能来完成任务
相反,您可以只使用现有的dictionary方法,如下所示:
class Class:
def __init__(self, **kwargs):
self.priceTable = kwargs.copy()
def get_price(self, reqId):
return self.priceTable.get(reqId, None)
inst = Class(id1=1.23, id2=2.34, id3=3.56)
print(inst.get_price('id2')) # -> 2.34
print(inst.get_price('id9')) # -> None
我无法让您所说的代码在没有异常的情况下运行(TypeError:字符串索引必须是整数
)-因此不清楚您在问什么。乍一看,你似乎不知道表达式是做什么的,也不知道如何使用它们。请改进您的问题,使其中的代码至少能再现问题(或者在本例中是您声称的版本)。谢谢,您正确理解了我的问题。然而,priceTable是一个包含多个键的字典列表,所以我认为Barmar的解决方案是最好的选择。