【问题标题】:Merge Tables with Remainders - Lua将表与余数合并 - Lua
【发布时间】:2016-02-25 02:42:53
【问题描述】:

我拥有的是一个嵌套表(两级)。我要做的是合并(展平?)子表,任何重复项都会溢出到新键中。 所以输入看起来像

t = {
  [1]  = {
    [1] = "One",
    [3] = "Three"
  },
  [2] = {
    [2] = "Two",
    [3] = "Three"
  },
  [3] = {
    [1] = "One",
    [2] = "Two",
    [4] = "Four"
  }
}

输出看起来像

t = {
  [1] = {
    [1] = "One",
    [2] = "Two",
    [3] = "Three",
    [4] = "Four"
  }  
  [2] = {
    [1] = "One",
    [2] = "Two",
    [3] = "Three"
  }
}

输入表最多有 1000 个键,所以我希望它可以高效地完成。

【问题讨论】:

  • tab[1] 对于它所在的每个表是否都相同? [1] = "Four"可以有一张桌子吗?
  • 是的,这些值只是举例。键总是 1-4,但值通常是不同的类型。

标签: lua


【解决方案1】:
local bottom, max_btm = {}, 0
for top = #t, 1, -1 do
  for k, v in pairs(t[top]) do
    local btm = bottom[k] or 0
    if btm < top then
      repeat btm = btm + 1
      until btm == top or not t[btm][k]
      if btm ~= top then
        t[btm][k], t[top][k] = v
      end
      bottom[k] = btm
      max_btm = math.max(max_btm, btm)
    end
  end
  if max_btm < top then
    t[top] = nil
  end
end

【讨论】:

    【解决方案2】:

    试试这个:

    local d={}
    for k,v in pairs(t) do
        if k~=1 then
            for kk,vv in pairs(v) do
                if t[1][kk]==nil then
                    t[1][kk]=vv
                else
                    d[kk]=vv
                end
            end
            t[k]=nil
        end
    end
    t[2]=d
    

    【讨论】:

    • 如何处理大量余数?例如,假设 [2] = "Two" 有两个余数
    • @user142532,上面的代码只保留每个副本的副本,如果这不适合您,您必须更准确地指定您的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多