在 elixir 里,我有个列表,大概是这样:
[
%{id: 1, retweet_count: 10, favorite_count: 20},
%{id: 2, retweet_count: 20, favorite_count: 1},
%{id: 3, retweet_count: 15, favorite_count: 50},
]
现在想按 retweet_count 与 favorite_count 的总数降序排列。
在 JavaScript 里,这非常简单:
list.sort(function (a, b) {
if (a.retweet_count + a.favorite_count > b.retweet_count + b.favorite_count) {
return -1
} else if (a.retweet_count + a.favorite_count < b.retweet_count + b.favorite_count) {
return 1
}
return 0
})
Elixir 有个类似的方法 sort_by:
sort(enumerable, fun)
于是我们的降序排列规则写成如下:
Enum.sort [
%{id: 1, retweet_count: 10, favorite_count: 20},
%{id: 2, retweet_count: 20, favorite_count: 1},
%{id: 3, retweet_count: 15, favorite_count: 50},
], &(Map.get(&1, :retweet_count) + Map.get(&1, :favorite_count) >= Map.get(&2, :retweet_count) + Map.get(&2, :favorite_count))
摩托车销售模拟器内置菜单中文版
摩托车出售模拟器,又名摩托车销售模拟器,这是一个以摩托车销售
船舶模拟2020最新版
船舶模拟2020是玩法非常有意思的模拟驾驶游戏,高清3d画质
油管主播的生活2内置菜单版
油管主播的生活2内置菜单版是一款模拟养成类游戏,在这里你将体
网吧老板模拟器2手机版
网吧老板模拟器2是非常受欢迎的模拟经营题材手游,在原本的基础
美国警察模拟器巡警2024最新版
美国警察模拟器是一款好玩的模拟手游,游戏中你将扮演一位警察,