Tag: if语句

C# – 在if语句中赋值

我有一个类Animal ,它的子类Dog 。 我经常发现自己编码如下: if (animal is Dog) { Dog dog = animal as Dog; dog.Name; … } 对于可变的Animal animal; 。 有没有一些语法可以让我写下如下的东西: if (Dog dog = animal as Dog) { dog.Name; … }

“if a或b或c但不是全部”的Python语法

我有一个python脚本,可以接收零或三个命令行参数。 (它可以运行默认行为或需要指定所有三个值。) 什么是类似的理想语法: if a and (not b or not c) or b and (not a or not c) or c and (not b or not a): ?

切换if-else语句的优点

使用switch语句的最佳做法是使用30个unsigned枚举的if语句,其中大约10个具有预期的操作(目前是相同的操作)。 性能和空间需要考虑,但并不重要。 我已经抽象了这个片段,所以不要因为命名惯例而恨我。 switch语句: // numError is an error enumeration type, with 0 being the non-error case // fire_special_event() is a stub method for the shared processing switch (numError) { case ERROR_01 : // intentional fall-through case ERROR_07 : // intentional fall-through case ERROR_0A : // intentional fall-through case ERROR_10 : // intentional fall-through case […]

Golang是否具有“如果x in”构造与Python类似?

没有迭代整个数组我怎么检查数组中的'X'在Go? 像Python: if "x" in array: …

Python如果不是== vs if!=

这两行代码有什么区别: if not x == 'val': 和 if x != 'val': 比另一个更有效率吗? 使用会更好吗? if x == 'val': pass else:

Kotlin三元条件运算符

Kotlin中这个expression的等价物是什么? a ? b : c 这不是Kotlin中的有效代码。

如何缩短我的条件陈述

我有一个非常长的条件声明,如下所示: if(test.type == 'itema' || test.type == 'itemb' || test.type == 'itemc' || test.type == 'itemd'){ // do something. } 我想知道是否可以将这个expression/陈述重构成更简洁的forms。 任何想法如何实现这一目标?

如果…按照概率进行sorting,sorting的效果如何?

具体来说,如果我有一系列if … else if语句,而且事先知道每个语句的相对概率都是true ,那么它在执行时间上有多大的区别呢? 例如,我应该喜欢这个: if (highly_likely) //do something else if (somewhat_likely) //do something else if (unlikely) //do something 这个? if (unlikely) //do something else if (somewhat_likely) //do something else if (highly_likely) //do something 看起来很明显,sorting的版本会更快,但是为了可读性或副作用的存在,我们可能想要对它们进行非最优sorting。 在实际运行代码之前,也很难判断CPU如何处理分支预测。 所以在试验过程中,我最终回答了自己的一个具体案例的问题,但是我也希望听到其他意见/见解。 重要的是:这个问题假设if语句可以被任意地重新sorting而不会对程序的行为产生任何其他影响。 在我的回答中,三个条件testing是相互排斥的,不会产生副作用。 当然,如果这些陈述必须以一定的顺序进行评估以达到一些理想的行为,那么效率问题就没有意义了。

Python语句的else语句

我注意到下面的代码在Python中是合法的。 我的问题是为什么? 有没有特定的原因? n = 5 while n != 0: print n n -= 1 else: print "what the…"

如果和foreach分离

我有一个foreach循环和一个if语句。 如果find一场比赛,我需要最终摆脱这个问题。 foreach($equipxml as $equip) { $current_device = $equip->xpath("name"); if ( $current_device[0] == $device ) { // found a match in the file $nodeid = $equip->id; <break out of if and foreach here> } }