Lambda函数中的多个if语句 [英] Multiple if statements in a lambda function
问题描述
我正在尝试在python lambda函数中使用3 if语句.这是我的代码:
I am trying to use 3 if statements within a python lambda function. Here is my code:
y=lambda symbol: 'X' if symbol==True 'O' if symbol==False else ' '
例如,我已经能够获得两个if语句来正常工作
I Have been able to get two if statements to work just fine e.g.
x=lambda cake: "Yum" if cake=="chocolate" else "Yuck"
基本上,我希望lambda函数使用if语句在符号为True时返回'X',在符号为false时返回'O',否则返回''.我什至不确定这是否可行,但是我无法在互联网上找到任何信息,因此,我非常感谢您的帮助:)
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 :)
推荐答案
您在'O'
之前缺少else
. 这有效:
You are missing an else
before 'O'
. This works:
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.
这篇关于Lambda函数中的多个if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!