Elixir Enum.sort没有正确排序

时间:2016-05-25 15:40:56

标签: sorting elixir

我在尝试对Elixir中的结构列表进行排序时遇到了一些问题......

我无法找出我做错了什么。

IO.puts "########### MY TOP 5 #############"
IO.inspect mytop5
IO.puts "=================================" 
sorted = Enum.sort_by(mytop5, &(&1.count))
IO.inspect sorted
IO.puts "------------------------"

这是结果

iex(67)> ########### MY TOP 5 #############
iex(67)> [%{count: "3", from: "AUD", rate: 0.64536947, to: "EUR"},
%{count: "10", from: "USD", rate: 1.3876, to: "AUD"},
%{count: "11", from: "USD", rate: 0.89726335, to: "EUR"}]
iex(67)> =================================
iex(67)> [%{count: "3", from: "AUD", rate: 0.64536947, to: "EUR"},
%{count: "11", from: "USD", rate: 0.89726335, to: "EUR"},
%{count: "10", from: "USD", rate: 1.3876, to: "AUD"}]
iex(67)> ------------------------

while:

iex(3)> [%{plop: "aze", count: 5, name: "a"}, %{plop: "aze", count: 1, name: "p"}, %{plop: "aze", count: 45, name: "e"}] |> Enum.sort_by(&(&1.count))
[%{count: 1, name: "p", plop: "aze"}, %{count: 5, name: "a", plop: "aze"},
 %{count: 45, name: "e", plop: "aze"}]

1 个答案:

答案 0 :(得分:5)

这是基于count字符串的排序:

Enum.sort(["3", "10", "5"])# ["10", "3", "5"]
Enum.sort([3, 10, 5])      # [3, 5, 10]

这是因为"10" < "3"由于第一个字符而成立:

Enum.sort(["30", "9", "10", "1", "100", "3"])
# ["1", "10", "100", "3", "30", "9"]

您可以使用String.to_integer/1进行转换:

Enum.sort_by(mytop5, &(String.to_integer(&1.count)))