如何通过Lua的“分数”和“索引”对内部表进行排序?
我已经存储在变量T
以下的Lua表:如何通过Lua的“分数”和“索引”对内部表进行排序?
{
["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.表具有较高score
都放在顶端。
2.等于score
的表格按其index
排序。
{
[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
(降序)排序,然后按index
(升序)排序相同的得分。
像这样的东西应该工作:
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)
感谢您的帮助! :d – Pojat
在lua中,表格包含两个数据结构:数组和字典。
排序装置排序阵列,其中每个元件与数字索引和索引相关联的是连续的是:1,2,3 ...
您初始表实际上是一个字典 - 每个条目有一个任意关键的关键(在你的情况下,那些是字符串)。
因此,你所描述的实际上并不是一个排序任务,你最终需要一个不同类型的表。
table.sort
适用于lua表的数组部分,也就是那些索引从1开始到第一个零结束的元素。
a={s=3,['r']=3, 5,3,2, nil,21}
|these|
|ones |
所以,首先要创建一个数组和排序一句:
local sorted={}
for k,v in pairs(T) do
table.insert(sorted,v)
end
table.sort(sorted,function(a,b)
--your code here
--function should return true if element `a` from the array `sorted`
--must be higher (to the left of) `b`
end)
或者,你可以在条目存储在无论是在字典和阵列部分相同的表中,table.sort
功能会忽略字典。但使用pairs
循环表并不明智,并且同时添加新元素。因此,惯用的方式仍然涉及中间复制。
感谢您的解释。 – Pojat
https://devdocs.io/lua~5.3/index#pdf-table.sort – hjpotter92
我明白,我必须使用'table.sort' Lua的功能但是,我不知道如何在这种情况下使用它。 – Pojat