如何按实际部分对复数进行排序

Ste*_*iew 5 julia

我想对复数的列表(或julia说一维数组)进行排序,通过实数,然后是复数的虚部.我尝试使用匿名函数,但它不起作用.

julia> b=[3 + 1im,1 + 2im,1 + 1im,5 + 6im]
4-element Array{Complex{Int64},1}:
 3 + 1im
 1 + 2im
 1 + 1im
 5 + 6im

julia> sort(b,lt = x,y -> if(real(x)==real(y)) imag(x)<imag(y) else real(x)<real(y) end)
ERROR: UndefVarError: x not defined
Stacktrace:
 [1] top-level scope at none:0
Run Code Online (Sandbox Code Playgroud)

我想要以下结果

 1 + 1im
 1 + 2im
 3 + 1im
 5 + 6im
Run Code Online (Sandbox Code Playgroud)

Jam*_*ook 6

很近!

julia> sort(b, lt = (x,y) -> real(x)==real(y) ? imag(x)<imag(y) : real(x)<real(y))
4-element Array{Complex{Int64},1}:
 1+1im
 1+2im
 3+1im
 5+6im
Run Code Online (Sandbox Code Playgroud)

  • 稍微短一点就是使用`by`这样:`sort(b,by = x - >(real(x),imag(x)))`并使用按字典顺序对元组进行排序的事实. (7认同)