Python lambda 函数中的多个 if 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33439434/
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
Multiple if statements in a lambda function
提问by Rational Function
I am trying to use 3 if statements within a python lambda function. Here is my code:
我正在尝试在 python lambda 函数中使用 3 个 if 语句。这是我的代码:
y=lambda symbol: 'X' if symbol==True 'O' if symbol==False else ' '
I Have been able to get two if statements to work just fine e.g.
我已经能够让两个 if 语句正常工作,例如
x=lambda cake: "Yum" if cake=="chocolate" else "Yuck"
Essentially, I want a lambda function to use if statements to return 'X' if the symbol is True, 'O' if it is false, and ' ' otherwise. I'm not even sure if this is even possible, but I haven't been able to find any information on the internet, so I would really appreciate any help :)
本质上,我希望 lambda 函数使用 if 语句在符号为 True 时返回 'X',如果为假则返回 'O',否则返回 ' '。我什至不确定这是否可能,但我无法在互联网上找到任何信息,所以我非常感谢任何帮助:)
采纳答案by Cristian Lupascu
You are missing an else
before 'O'
. Thisworks:
你缺少一个else
before 'O'
。这有效:
y = lambda symbol: 'X' if symbol==True else 'O' if symbol==False else ' '
However, I think you should stick to Adam Smith's approach. I find that easier to read.
但是,我认为您应该坚持亚当·斯密的方法。我觉得这更容易阅读。
回答by Adam Smith
You can use an anonymous dict inside your anonymous function to test for this, using the default value of dict.get
to symbolize your final "else"
您可以在匿名函数中使用匿名 dict 来对此进行测试,使用默认值 ofdict.get
来表示您最终的“else”
y = lambda sym: {False: 'X', True: 'Y'}.get(sym, ' ')