我将以下 Lua 表存储在变量 T
中:
{
["mn"] = { ["index"] = 7, ["key"] = "mn", ["score"] = 0 },
["kl"] = { ["index"] = 6, ["key"] = "kl", ["score"] = .4 },
["ef"] = { ["index"] = 3, ["key"] = "ef", ["score"] = .3 },
["ab"] = { ["index"] = 1, ["key"] = "ab", ["score"] = 0 },
["cd"] = { ["index"] = 2, ["key"] = "cd", ["score"] = .1 },
["gh"] = { ["index"] = 4, ["key"] = "gh", ["score"] = 0 },
["ij"] = { ["index"] = 5, ["key"] = "ij", ["score"] = .2 }
}
我想按以下方式对 T
表的所有内表进行排序:
1.分数
较高的表格放在顶部。
2. 分数
相等的表按其索引
排序。
因此,排序后,应在输出上生成以下顺序表:
{
[1] = { ["index"] = 6, ["key"] = "kl", ["score"] = .4 }, -- highest "score"
[2] = { ["index"] = 3, ["key"] = "ef", ["score"] = .3 },
[3] = { ["index"] = 5, ["key"] = "ij", ["score"] = .2 },
[4] = { ["index"] = 2, ["key"] = "cd", ["score"] = .1 },
[5] = { ["index"] = 1, ["key"] = "ab", ["score"] = 0 }, -- lowest "score", lowest "index"
[6] = { ["index"] = 4, ["key"] = "gh", ["score"] = 0 }, -- when scores are the same, sort by their "index" instead
[7] = { ["index"] = 7, ["key"] = "mn", ["score"] = 0 } -- lowest "score", highest "index"
}
如何完成这个Lua表排序?
最佳答案
您需要首先将拥有的哈希值转换为表,然后使用自定义排序函数对该表的元素进行排序,该函数按 score
(降序)排序,然后按 具有相同分数的元素的索引
(升序)。
这样的事情应该有效:
local hash = {
["mn"] = { ["index"] = 7, ["key"] = "mn", ["score"] = 0 },
["kl"] = { ["index"] = 6, ["key"] = "kl", ["score"] = .4 },
["ef"] = { ["index"] = 3, ["key"] = "ef", ["score"] = .3 },
["ab"] = { ["index"] = 1, ["key"] = "ab", ["score"] = 0 },
["cd"] = { ["index"] = 2, ["key"] = "cd", ["score"] = .1 },
["gh"] = { ["index"] = 4, ["key"] = "gh", ["score"] = 0 },
["ij"] = { ["index"] = 5, ["key"] = "ij", ["score"] = .2 }
}
local tbl = {}
for _,v in pairs(hash) do
table.insert(tbl, v)
end
table.sort(tbl, function(a,b)
return a.score > b.score or a.score == b.score and a.index < b.index
end)
关于sorting - 如何在Lua中按 "score"然后 "index"对内表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46117999/