sorting - 如何在Lua中按 "score"然后 "index"对内表进行排序?

标签 sorting lua lua-table

我将以下 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/

相关文章:

javascript - 数据表 - 无法按与字符串类型不同的列排序

sql - 在同一列上按升序或降序有条件地排序

redis - PHP Redis Lua 脚本问题

表中的 Lua 拉丁字符

types - 表中的 Lua 表显示为 Nil

javascript - 创建一个在 2 个不同值之间交替的数组

java - 如何将已排序的索引映射回我正在排序的集合的原始索引

audio - 电晕:重新创建场景后,音频不会再开始播放

function - 使两个使用函数创建的对象可触摸(LUA、Corona)

lua - table.unpack() 只返回第一个元素