【问题标题】:subtract table from table in Lua从 Lua 中的表中减去表
【发布时间】:2014-04-14 15:11:50
【问题描述】:

我正在尝试从 Lua 中的表中减去表,因此返回表将是 t1 与 t2 的减法。

这似乎有效,但有没有更有效的方法?

 function array_sub(t1, t2)

-- Substract Arrays from Array 
-- Usage: nretable =  array_sub(T1, T2)  -- removes T1 from T2

 table.sort( t1 )

for i = 1, #t2 do
    if (t2[i] ~= nil) then
      for j = 1, #t1 do
        if (t2[i] == t1 [j]) then
        table.remove (t2, i)
        end
      end
    end
end
    return t2
end


local remove ={1,2,3} 
local full = {}; for i = 1, 10 do full[i] = i end

local test ={}

local test =  array_sub(remove, full)

for i = 1, #test do
  print (test[i])
end

【问题讨论】:

    标签: lua lua-table


    【解决方案1】:

    是的,有:制作一个包含表 t1 的所有值的查找表,然后从表 t2 的末尾开始。

    function array_sub(t1, t2)
      local t = {}
      for i = 1, #t1 do
        t[t1[i]] = true;
      end
      for i = #t2, 1, -1 do
        if t[t2[i]] then
          table.remove(t2, i);
        end
      end
    end
    

    交易了O(#t1) 空间以换取从O(#t1*#t2)O(#t1+#t2) 的加速。

    【讨论】:

      【解决方案2】:

      您只需使用减号减去表格。

      例如

      local t2 = {'a', 'b', 'c', 'd', 'e'}
      local t1 = {'b', 'e', 'a'}
      
      t2 = t2 - t1
      
      -- t2 new value is {'c', 'd', 'd'}
      

      【讨论】:

      • 在原生 Lua 中,标准表值没有实现算术运算!您提供的代码会导致错误...
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-24
      • 1970-01-01
      相关资源
      最近更新 更多