Jor*_*ier 5 syntax if-statement conditional-operator conditional-statements julia
考虑 Julia 中的三元运算符
julia> x = 1 ; y = 2
julia> println(x < y ? "less than" : "not less than")
less than
Run Code Online (Sandbox Code Playgroud)
问题:有没有办法省略:语句的一部分?相当于
if condition
# dosomething
end
Run Code Online (Sandbox Code Playgroud)
没有写,如果条件不满足,什么都不应该做。
Prz*_*fel 13
做就是了:
condition && do_something
Run Code Online (Sandbox Code Playgroud)
例如:
2 < 3 && println("hello!")
Run Code Online (Sandbox Code Playgroud)
解释:
&&是 Julia 中的短路算子。因此,仅在需要评估时才会评估第二个值。因此,当第一个condition评估为时,false不需要评估第二个部分。
最后,请注意,您也可以在作业中使用它:
julia> x = 2 > 3 && 7
false
julia> x = 2 < 3 && 7
7
Run Code Online (Sandbox Code Playgroud)
然而,这会使x类型不稳定,因此您可能希望将赋值的右侧包裹起来,Int例如x = Int(2 > 3 && 7)您x将始终是Int.
&&通常用于此,因为它很短,但您必须知道阅读它的技巧。我有时发现只使用常规的旧 if 语句更具可读性。在 Julia 中,如果你想节省空间,它不需要跨多行。
julia> x = 1; y = 2;
julia> if (x < y) println("less than") end
less than
julia> if (x > y) println("greater than") else println("not greater than") end
not greater than
Run Code Online (Sandbox Code Playgroud)
请注意,在这种情况下,条件周围不需要括号;我只是为了清楚起见添加了它们。另外,请注意,println为了清楚起见,我移到字符串旁边,但如果您愿意,您可以将整个if语句放在 里面println,就像您在问题中所做的那样。
| 归档时间: |
|
| 查看次数: |
143 次 |
| 最近记录: |