考虑 Julia 中的三元运算符
julia> x = 1 ; y = 2
julia> println(x < y ? "less than" : "not less than")
less than
问题:有没有办法省略 :
声明的一部分?相当于if condition
# dosomething
end
没有写,如果条件不满足,什么都不应该做。注意:我研究了答案,但没有任何结果,即使在相关问题( 1 , 2 )
最佳答案
做就是了:
condition && do_something
例如:2 < 3 && println("hello!")
解释:&&
是 Julia 中的短路算子。因此,仅在需要评估时才会评估第二个值。因此当第一个 condition
计算结果为 false
没有必要评估第二部分。最后,请注意,您也可以在作业中使用它:
julia> x = 2 > 3 && 7
false
julia> x = 2 < 3 && 7
7
然而,这使得 x
输入不稳定,因此您可能希望将赋值的右侧包裹在 Int
周围如 x = Int(2 > 3 && 7)
比你的x
将永远是 Int
.
关于if-statement - 没有 `else` 的 Julia 三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67076389/