【问题标题】:Remove duplicate tables in a nested table. Lua删除嵌套表中的重复表。卢阿
【发布时间】:2026-02-09 18:50:01
【问题描述】:

在将此问题标记为与this 重复之前,请阅读全文:

我在 Lua 中有一个表,它是一个类似于下面的表,我想删除其中的所有重复表。

table1 = {{1, 2, 3}, {1, 2, 3}, {1, 2, 3, 4}}

我想要做的是删除重复的表并只使用一个。结果应该如下所示

table2 = {{1, 2, 3}, {1, 2, 3, 4}}

我尝试了很多我在网上找到的方法以及我自己的一些方法,但我无法做到。

这是我上次尝试的方法

local test = {1,2,4,2,3,4,2,3,4,"A", "B", "A"}
local hash = {}
local res = {}

for _,v in ipairs(test) do
   if (not hash[v]) then
       res[#res+1] = v -- you could print here instead of saving to result table if you wanted
       hash[v] = true
   end

end

-- Here the test is the input, and res is the output table without 
-- any duplicates but this works only for values in it and not for
-- nested tables.

请帮帮我。

【问题讨论】:

  • 除了在网上搜索解决方案,您真的考虑过这个问题吗?比如拿起笔和纸,一步一步地写下你必须做的事情?你不需要成为程序员来解决这样的问题。
  • 是的,我做到了,给我时间到明天,我看看能不能得到答复。
  • 在测试hash[ser(v)]之前需要将v序列化成字符串

标签: lua duplicates lua-table nested-table


【解决方案1】:

让我们拿起笔和纸思考一下。

我们有什么?

包含多个表的表。根据您的示例,这些内表是序列。所以它们只有从 1 开始的连续整数键。内表的元素要么是字符串,要么是数字。

您想要删除重复的内表,该表与之前的另一个表具有相同的元素。

那我们该怎么办?

我们需要遍历我们的表格并检查每个元素,并询问我们之前是否看过这个内部表格的内容。

所以我们列出了我们以前见过的序列。

1) Check if the next element is already on the list.
2) If it is on the list, remove it, else put it on the list.
3) back to 1 

现在把它翻译成 Lua

local table1 = {{1, 2, 3}, {1, 2, 3}, {1, 2, 3, 4}}

-- make a list to add what we already have seen
local list = {}
-- make a list of unique items as it is easier than removing items from our input list
local results = {}
-- go over the list and check each element
for i, innerTable in ipairs(table1) do
  -- convert it to a string representation so we add it to our list easily
  local serialized = table.concat(innerTable, "\x1f")
  -- only if it is not on our list yet
  if not list[serialized] then
    -- add it to the list
    table.insert(results, innerTable)
    -- add the item to the result list
    list[serialized] = true
  end
end

-- print the results
for i,v in ipairs(results) do print(v) end

【讨论】: