【问题标题】:How to sort complex numbers by real part follow by imaginary part如何按实部对复数进行排序,然后是虚部
【发布时间】:2018-08-17 17:18:58
【问题描述】:

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

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

我想要以下结果

 1 + 1im
 1 + 2im
 3 + 1im
 5 + 6im

【问题讨论】:

    标签: julia


    【解决方案1】:

    如此接近!

    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
    

    【讨论】:

    • 使用by 像这样更短一点:sort(b, by = x -&gt; (real(x), imag(x))) 并使用元组按字典顺序排序的事实。
    【解决方案2】:

    元组按字典顺序排序(第一个元素;然后是第二个元素,依此类推)。 你可以这样做:

    b = [3 + 1im, 1 + 2im, 1 + 1im, 5 + 6im]
    sort(b, lt = (x, y) -> (real(x), imag(x)) < (real(y), imag(y)))
    

    编辑:上面的评论,使用by=,更简洁。

    【讨论】:

      猜你喜欢
      • 2020-07-12
      • 2019-03-02
      • 1970-01-01
      • 2018-02-17
      • 2011-09-25
      • 2012-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多