如果Python没有三元条件运算符,是否可以使用其他语言结构模拟一个?
在Perl(和其他语言)中,条件三元运算符可以表示如下:
my $foo = $bar == $buz ? $cat : $dog;
Run Code Online (Sandbox Code Playgroud)
VB.NET中是否有类似的运算符?
如何? :在Ruby中使用条件运算符()?
例如,这是正确的吗?
<% question = question.size > 20 ? question.question.slice(0, 20)+"..." : question.question %>
Run Code Online (Sandbox Code Playgroud) 没有别的,我可以写'if else'速记吗?
var x=1;
x==2 ? dosomething() : doNothingButContinueCode();
Run Code Online (Sandbox Code Playgroud)
我注意到if else了其他的工作(但我不知道为什么或者这是个好主意).
编辑:有些人似乎很困惑为什么我会费心去尝试这个.请放心,这纯粹是出于好奇.我喜欢乱搞JavaScript.
如何if在JavaScript中使用内联语句?还有内联else声明吗?
像这样的东西:
var a = 2;
var b = 3;
if(a < b) {
// do something
}
Run Code Online (Sandbox Code Playgroud) javascript if-statement ternary-operator conditional-operator
这行代码是什么意思?
label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;
Run Code Online (Sandbox Code Playgroud)
在?和:迷惑我.
在C/C++(以及该系列的许多语言)中,根据条件声明和初始化变量的常用习惯用法是使用三元条件运算符:
int index = val > 0 ? val : -val
Run Code Online (Sandbox Code Playgroud)
Go没有条件运算符.实现上述相同代码的最惯用方法是什么?我来到以下解决方案,但它似乎相当冗长
var index int
if val > 0 {
index = val
} else {
index = -val
}
Run Code Online (Sandbox Code Playgroud)
还有更好的东西吗?
我读的是无处不在三元运营商应该是比快,或至少一样的,它的等效if- else块.
但是,我做了以下测试,发现事实并非如此:
Random r = new Random();
int[] array = new int[20000000];
for(int i = 0; i < array.Length; i++)
{
array[i] = r.Next(int.MinValue, int.MaxValue);
}
Array.Sort(array);
long value = 0;
DateTime begin = DateTime.UtcNow;
foreach (int i in array)
{
if (i > 0)
{
value += 2;
}
else
{
value += 3;
}
// if-else block above takes on average 85 ms
// OR I can use a ternary operator:
// value += …Run Code Online (Sandbox Code Playgroud) 我刚刚遇到一个奇怪的错误:
private bool GetBoolValue()
{
//Do some logic and return true or false
}
Run Code Online (Sandbox Code Playgroud)
然后,在另一种方法中,这样的事情:
int? x = GetBoolValue() ? 10 : null;
Run Code Online (Sandbox Code Playgroud)
很简单,如果方法返回true,则为Nullable intx 赋值10 .否则,将null赋给nullable int.但是,编译器抱怨:
错误1无法确定条件表达式的类型,因为
int和之间没有隐式转换<null>.
我疯了吗?
operators ×3
c# ×2
javascript ×2
syntax ×2
.net ×1
bash ×1
c ×1
go ×1
if-statement ×1
nullable ×1
objective-c ×1
performance ×1
python ×1
ruby ×1
shorthand ×1
vb.net ×1