我正在编写一些lambda函数,但无法解决这个问题.有没有办法lambda x: x if (x<3)
在python中有类似的东西?由于lambda a,b: a if (a > b) else b
工作正常.到目前为止lambda x: x < 3 and x or None
似乎是我发现的最接近的.
我今天正在研究一个项目,发现自己在几个地方使用Math.Max,并在其他地方使用内联if语句.所以,我想知道是否有人知道哪个更"好"......或者更确切地说,真正的差异是什么.
例如,在下面,c1 = c2
:
Random rand = new Random();
int a = rand.next(0,10000);
int b = rand.next(0,10000);
int c1 = Math.Max(a, b);
int c2 = a>b ? a : b;
Run Code Online (Sandbox Code Playgroud)
我是专门询问C#,但我想不同语言的答案可能会有所不同,但我不确定哪些有类似的概念.
我想写一些类似的东西:
@( checkCondition ? "<span class='label'>Right!</span>" : "")
Run Code Online (Sandbox Code Playgroud)
但它显示的是源代码而不是HTML,有一种简单的方法可以做到这一点吗?
谢谢!
使用'?:'条件和简单的'if-then-else'语句之间有区别吗?它只是另一种方式,或者它实际上使用更少的空间/花费更少的时间来阅读比'if'语句?
例:
如果声明:
if (item1.isEqualToString:@"2") //If statement
[self doSomething];
else
[self doSomethingElse];
item1.isEqualToString:@"2" ? [self doSomething] : [self doSomethingElse]; //'?:' statement
Run Code Online (Sandbox Code Playgroud) conditional if-statement objective-c conditional-operator inline-if
在《Dive in to Python》中,我了解了and
and运算符的特殊性质,以及如何通过and-oror
技巧使用布尔运算符的短路求值来更简洁地表达条件,该技巧与 C 中的三元运算符非常相似。
C:
result = condition ? a : b
Run Code Online (Sandbox Code Playgroud)
Python:
result = condition and a or b
Run Code Online (Sandbox Code Playgroud)
这似乎很方便,因为 lambda 函数在 Python 中仅限于单行函数,但它使用逻辑语法来表达控制流。
自 Python 2.5 以来,inline-if
似乎已经作为一种更易读的语法来拯救 and-or 技巧:
result = a if condition else b
Run Code Online (Sandbox Code Playgroud)
所以我猜想这是可读性较差的 and-or-construct 的 pythonic 替代品。即使我想嵌套多个条件,它看起来仍然相当全面:
result = a if condition1 else b if condition2 else c
Run Code Online (Sandbox Code Playgroud)
但在一个充满不确定性的世界中,我经常发现自己编写一些类似这样的代码来访问 abc :
result = a and hasattr(a, 'b') and hasattr(a.b, 'c') and a.b.c …
Run Code Online (Sandbox Code Playgroud) python lambda short-circuiting inline-if conditional-statements
我对Python中的if和inline之间的区别有点好奇.哪一个更好?
是否有任何理由使用内联,除了它更短的事实?
此外,这个陈述有什么问题吗?我收到语法错误:SyntaxError: can't assign to conditional expression
a = a*2 if b == 2 else a = a/w
Run Code Online (Sandbox Code Playgroud) 我想在内联if语句中编写lambda表达式.但内联if语句必须具有强类型结果.
MyType obj = someObj.IsOk ? null : () => {
MyType o = new MyType(intVal);
o.PropertyName = false;
return o;
};
Run Code Online (Sandbox Code Playgroud)
当然这不起作用,因为lambda表达式不是强类型的.我想到了使用Func<intVal, MyType>
委托,使其成为强大的类型.
但是我如何使用Func<>
内联如果?我是否必须在外部定义自己的函数并在内联if语句中使用它?
public class Foo : IFooBarable {...}
public class Bar : IFooBarable {...}
Run Code Online (Sandbox Code Playgroud)
那么为什么这不会编译......
int a = 1;
IFooBarable ting = a == 1 ? new Foo() : new Bar();
Run Code Online (Sandbox Code Playgroud)
但这会......
IFooBarable ting = a == 1 ? new Foo() : new Foo();
IFooBarable ting = a == 1 ? new Bar() : new Bar();
Run Code Online (Sandbox Code Playgroud) inline-if ×8
c# ×3
lambda ×3
python ×3
if-statement ×2
.net-3.5 ×1
asp.net-mvc ×1
conditional ×1
interface ×1
objective-c ×1
razor ×1