【问题标题】:Lua rough sort, then fine sortLua 粗排序,然后是细排序
【发布时间】:2018-09-16 05:38:13
【问题描述】:

假设我在 Lua 中有这张表:

items = {
    {7007, "quux", 9.7},
    {1004, "foo", 12.3},
    {1234, "bar", 9.6},
    {1234, "baz", 8.8},
}

我是这样排序的:

function compare(a,b)
  return a[1] < b[1]
end

table.sort(items, compare)

这将导致表格按第一项排序,但由于其中两项的值为“1234”,因此它们之间的相对位置是任意的。

我将如何对表格进行第二次排序,以便“1234”保持其在表格中的绝对位置,但使用第三个值(9.6 和 8.8)进行更精细的排序?

【问题讨论】:

    标签: sorting lua lua-table


    【解决方案1】:

    您只需在比较函数中添加更多逻辑即可。 compare 函数的返回值告诉 Lua 哪一项是最先出现的。如果返回 true,则 a 先出现,否则 b 先出现。

    function compare(a,b)
      if a[1] == b[1] then
        return a[3] < b[3]
      else
        return a[1] < b[1]
      end
    end
    

    或更短:

    function compare(a,b)
      return a[1] < b[1] or a[1] == b[1] and a[3] < b[3]
    end
    

    这很简单。对于您的一个非常相似的问题,您能听从我的最后建议吗?拿一张纸,用英语或任何你的母语写下你将如何解决这个问题。

    如果 a[1] 小于 b[1],则 a 出现在 b 之前, 否则,如果 a[1] 等于 b[1],如果 a[3] 小于 b[3],则 a 先出现。

    如果你把它翻译成 Lua,它看起来像:

    function compare(a, b)
      if a[1] < b[1] then
        return true
      elseif a[1] == b[1] then
        if a[3] < b[3] then
          return true
        end
      end
    end
    

    这也有效,但你可以写得更紧凑,就像我上面展示的那样。

    【讨论】:

      猜你喜欢
      • 2017-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-19
      • 1970-01-01
      • 1970-01-01
      • 2012-11-09
      • 1970-01-01
      相关资源
      最近更新 更多