如何按 Lua 中内部表的“分数”和“索引”对其进行排序?

我有以下存储在变量 T 中的 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 }, --最高“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 }, --最低“score”,最低“index”
    [6] = { ["index"] = 4, ["key"] = "gh", ["score"] = 0 }, --当分数相同时,按其“index”排序
    [7] = { ["index"] = 7, ["key"] = "mn", ["score"] = 0 } --最低“score”,最高“index”
}

如何完成这个 Lua 表排序?

点赞
用户4687565
用户4687565

在lua中,表包括两种数据结构:数组和字典。

排序意味着对数组进行排序,每个元素都与数字索引相关联,索引是连续的,即:1,2,3...

您的初始表实际上是一个字典-每个条目都有一个关联的任意键(在您的情况下,这些是字符串)。

因此,您所描述的实际上不是排序任务,您最终想要的是不同类型的表。

table.sort适用于lua表格的数组部分,也就是从1开始的索引元素,一直到第一个空条目。

a = {s = 3, ['r'] = 3, 5, 3, 2, nil, 21}
                 |这些|
                 |内容|

因此,您首先需要创建一个数组并对其进行排序:

local sorted={}
for k,v in pairs(T) do
  table.insert(sorted,v)
end
table.sort(sorted,function(a,b)
  --在这里编写您的代码
  --如果数组“sorted”的元素“a”必须更高(在“b”的左侧),
  --则该函数应返回true
end)

或者,您可以在同一张表格中同时存储字典和数组部分的条目,table.sort函数将忽略字典。但是,通过使用“对”循环遍历表并同时添加新元素并不明智。因此,惯用法仍然涉及中间副本的创建。

2017-09-08 15:26:33
用户1442917
用户1442917

你需要先将你的哈希转换成一个表格,然后使用一个自定义排序函数按 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)
2017-09-08 15:50:58