让外部循环遍历表格,让内部循环始终在外部元素之前开始一个元素 - 这样可以避免重复计算和将对象与自身进行比较。此外,如果您调用要检查table 的表,这可能会隐藏您要访问insert 的table 库。所以假设你调用你的输入表t:
for i = 1, #t do
for j = i+1, #t do
if( t[i].n == t[j].n ) then
table.insert(table2, t[i])
table.insert(table2, t[j])
end
end
end
不过,如果三个或更多元素具有相同的值n,您将多次添加其中的一些。您可以使用另一个表格来记住您已经插入了哪些元素:
local done = {}
for i = 1, #t do
for j = i+1, #t do
if( t[i].n == t[j].n ) then
if not done[i] then
table.insert(table2, t[i])
done[i] = true
end
if not done[j] then
table.insert(table2, t[j])
done[j] = true
end
end
end
end
我承认这不是很优雅,但是这里已经很晚了,我的大脑拒绝想一个更整洁的方法。
编辑:事实上......使用另一个表,您可以将其减少为一个循环。当您遇到新的n 时,您将在n 添加一个新值作为您的帮助表的键 - 该值将是您刚刚分析的t[i]。如果您遇到表中已经存在的 n,则将保存的元素和当前元素都添加到目标列表中 - 您还可以将辅助表中的元素替换为 true 或其他不是表:
local temp = {}
for i = 1, #t do
local n = t[i].n
if not temp[n] then
temp[n] = t[i]
else
if type(temp[n]) == "table" then
table.insert(table2, temp[n])
temp[n] = true
end
table.insert(table2, t[i])
end
end