lua中的高级表排序

时间:2014-08-09 21:27:42

标签: sorting lua lua-table

我正在尝试对高级表进行排序,但没有成功。

这是我的表结构:

{
    ["12345"] = {12345, "Something", {"Stuff"}},
    ["523544"] = {523544, "Something", {"Stuff"}},
    ["6744"] = {6744, "Something", {"Stuff"}},
    ["146"] = {146, "Something", {"Stuff"}},
    ["724572"] = {724572, "Something", {"Stuff"}},
    ["54"] = {54, "Something", {"Stuff"}},
    ["146"] = {146, "Something", {"Stuff"}},
    ["146"] = {146, "Something", {"Stuff"}},
    ["12345"] = {12345, "Something", {"Stuff"}},
    ["44"] = {44, "Something", {"Stuff"}},
}

我想从最好到最不喜欢的方式对它进行排序:

{
    ["724572"] = {724572, "Something", {"Stuff"}},
    ["523544"] = {523544, "Something", {"Stuff"}},
    ["12345"] = {12345, "Something", {"Stuff"}},
    ["12345"] = {12345, "Something", {"Stuff"}},
    ["6744"] = {6744, "Something", {"Stuff"}},
    ["146"] = {146, "Something", {"Stuff"}},
    ["146"] = {146, "Something", {"Stuff"}},
    ["146"] = {146, "Something", {"Stuff"}},
    ["54"] = {54, "Something", {"Stuff"}},
    ["44"] = {44, "Something", {"Stuff"}},
}

我在这里遇到了一些问题。

  1. 它不能保存2个等值的数字
  2. 我似乎无法从最大到最小的排序
  3. 至于为什么索引是字符串,如果我table[623258195] = "Example",该表将创建623258195索引,导致我的程序崩溃。

    至于为什么值是表,它存储其他重要信息,即表中第2和第3个值,第1个是索引的数字形式。

    我希望自己能够清楚,如果这被认为是一个重复的问题,我很抱歉,我在搜索的最后一小时内找不到帮助我的任何内容。

2 个答案:

答案 0 :(得分:1)

  1. 您需要修改数据结构,以支持具有相同ID /密钥的多个值:

    {
        [12345] = {
            {12345, "foo", {"bar"}}, -- You'll probably want to sort these somehow.
            {12345, "baz", {"qux"}}
        },
        [123] = {
            {123, "foo", {"bar"}}
        }
    }
    
  2. 您可以使用table.sort(tbl, f)以及索引表:

    local unsorted = {} -- Data, in your format, inside this table.
    local index = {} -- Table which will contain sorted keys (then you loop over this, get unsorted[k])
    for k in pairs(unsorted) do
        index[#index+1] = k -- Populate the keys to sort.
    end
    table.sort(index, function(a, b) 
     return b < a -- Order highest to lowest, instead of lowest - highest (default)
    end)
    
  3. 这里是完整的代码示例和结果。 http://ideone.com/thE1zP

答案 1 :(得分:0)

你不能排序&#34;哈希中的密钥,因为他们没有&#34;顺序&#34;就像表中键的整数序列那样。

您可以更改数据结构以将哈希值转换为表格,但更简单的方法可能是使用单独的表格只包含哈希键并对其值进行排序;当您需要以特定顺序从哈希中获取元素时,您只需遍历该表中的(已排序)元素,然后从哈希中检索元素。

在任何一种情况下,您都无法为您尝试的同一个密钥存储多个值:

{
...
    ["146"] = {146, "Something", {"Stuff"}},
    ["146"] = {146, "Something", {"Stuff"}},
    ["146"] = {146, "Something", {"Stuff"}},
...
}

您需要将它们存储在一个表中(并使用"146"键引用该表)或重新考虑为什么您需要使用相同键值的不同元素键。