我所拥有的是嵌套表(两级)。我要做的是合并(展平?)子表,任何重复项溢出到新键。 所以输入看起来像
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个键,所以我希望它能有效地完成。
答案 0 :(得分: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
答案 1 :(得分:2)
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