Python 将 lambdas 存储在字典中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14419925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Storing lambdas in a dictionary
提问by BlackVegetable
I have been trying to create a dictionary with a string for each key and a lambda function for each value. I am not sure where I am going wrong but I suspect it is either my attempt to store a lambda in a dictionary in the first place, or the fact that my lambda is using a shortcut operator.
我一直在尝试创建一个字典,其中每个键都有一个字符串,每个值都有一个 lambda 函数。我不确定我哪里出错了,但我怀疑这要么是我试图将 lambda 存储在字典中,要么是我的 lambda 使用快捷操作符的事实。
Code:
代码:
dict = {
'Applied_poison_rating_bonus':
(lambda target, magnitude: target.equipmentPoisonRatingBonus += magnitude)
}
The error being raised is SyntaxError: invalid syntaxand pointing right at my +=. Are shortcut operators not allowed in lambdas, or am I even farther off track than I thought?
引发的错误是SyntaxError: invalid syntax并指向我的+=. lambdas 中是否不允许使用快捷操作符,或者我是否比我想象的更偏离轨道?
For the sake of sanity, I have omitted hundreds of very similar pairs (It isn't just a tiny dictionary.)
为了理智起见,我省略了数百个非常相似的对(它不仅仅是一本小字典。)
EDIT:
编辑:
It seems my issue was with trying to assign anythingwithin a lambda expression. Howver, my issue to solve is thus how can I get a method that only knows the key to this dictionary to be able to alter that field defined in my (broken) code?
我的问题似乎是试图在 lambda 表达式中分配任何内容。但是,我要解决的问题是如何获得一种方法,该方法只知道该字典的键,以便能够更改在我的(损坏的)代码中定义的字段?
Would some manner of call to eval() help?
以某种方式调用 eval() 会有帮助吗?
EDIT_FINAL:
EDIT_FINAL:
The functools.partial() method was recommended to this extended part of the question, and I believe after researching it, I will find it sufficient to solve my problem.
functools.partial() 方法被推荐用于这个问题的扩展部分,我相信经过研究后,我会发现它足以解决我的问题。
采纳答案by Martijn Pieters
You cannot use assignments in a expression, and a lambdaonly takes an expression.
您不能在表达式中使用赋值,并且 alambda只接受一个表达式。
You can store lambdas in dictionaries just fine otherwise:
否则,您可以将 lambdas 存储在字典中就好了:
dict = {'Applied_poison_rating_bonus' : (lambda target, magnitude: target.equipmentPoisonRatingBonus + magnitude)}
The above lambdaof course only returns the result, it won't alter target.equimentPoisonRatingBonusin-place.
以上lambda当然只返回结果,它不会target.equimentPoisonRatingBonus就地改变。

