Julia 是否有一种优雅的方式去做;不在「;朱莉娅?
我正在尝试将python脚本转换为Julia。我正在检查以确保我以最理想的方式编写代码。请参阅以下代码:Julia 是否有一种优雅的方式去做;不在「;朱莉娅?,julia,Julia,我正在尝试将python脚本转换为Julia。我正在检查以确保我以最理想的方式编写代码。请参阅以下代码: julia> a = [1,2,3,4,5] 5-element Array{Int64,1}: 1 2 3 4 5 julia> if 1 in a print("1 is in a") end 1 is in a julia> if 6 not in a print("6 not in a")
julia> a = [1,2,3,4,5]
5-element Array{Int64,1}:
1
2
3
4
5
julia> if 1 in a
print("1 is in a")
end
1 is in a
julia> if 6 not in a
print("6 not in a")
end
ERROR: TypeError: non-boolean (Int64) used in boolean context
Stacktrace:
[1] top-level scope at REPL[6]:1
julia> push!(a, 6)
6-element Array{Int64,1}:
1
2
3
4
5
6
julia> if (6 in a) == true
print("6 in a")
end
6 not in a
julia> b = [1]
1-element Array{Int64,1}:
1
julia> if (6 in b) == true
print("6 in b")
end
我是否正确地进行了“不在”检查
julia> a = [1,2,3,4,5];
julia> 6 ∉ a
true
∉通过键入\notin
然后点击TAB键,可以在REPL中键入code>符号。当然,∈在
中键入\in
并点击选项卡,也可以使用code>符号代替
中的:
julia> 6 ∈ a
false
有时您需要一个矢量化版本:
julia> x = [2, 7];
julia> x .∉ Ref(a)
2-element BitArray{1}:
0
1
在这种情况下需要Ref
,以便在广播操作中将a
视为标量
编辑:
正如@SalchiPapa和@DNF在评论中指出的,您可以执行!(a中的6)
如果您希望避免使用Unicode字符。有时显示Unicode会有问题,具体取决于您的设置,您也可以像这样对整个表达式求反:x=[1,2,3];2英寸x!(2 in x)#(真、假)
有一个未决问题,请求使用代码>在中缀运算符前面:在这种情况下,您可以编写6!在
中。不过,它似乎哪儿也去不了。现在,最好使用!(6英寸a)
我想。