如何解决删除嵌套表中的重复表路亚
我在 Lua 中有一个表,它是一个类似于下面的表,我想删除其中的所有重复表。
table1 = {{1,2,3},{1,3,4}}
table2 = {{1,4}}
我尝试了很多我在网上找到的方法和我自己的一些方法,但我无法做到。
这是我上次尝试的
local test = {1,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.
请帮帮我。
解决方法
让我们拿起纸笔思考。
我们有什么?
一个包含多个表的表。根据您的示例,这些内部表是序列。所以它们只有从 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,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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。