我有一张桌子
test = {a= {1,2}, b= {1},c= {2,3}}
我希望输出像。
test_out = {ab={1,2}, bc = {1,2,3}, ac={1,2,3}}
答案 0 :(得分:1)
显然你想要的是设置操作。这是一种没有任何库的方法:
local test = {a = {1, 2}, b = {1}, c = {2, 3}}
local keys = {}
for k,_ in pairs(test) do keys[#keys+1] = k end
table.sort(keys)
local result = {}
local t1, t2, r, found
for i=1,#keys-1 do
for j=i+1,#keys do
t1 = test[keys[i]]
t2 = test[keys[j]]
r, found = {}, {}
for k=1,#t1 do
found[t1[k]] = true
r[k] = t1[k]
end
for k=1,#t2 do
if not found[t2[k]] then
r[#r+1] = t2[k]
end
end
result[keys[i] .. keys[j]] = r
end
end
结果在result
表中。如果您可以使用pl.Set
之类的集合库,则可以使用更少的代码执行此操作:
local test = {a = {1, 2}, b = {1}, c = {2, 3}}
local keys = {}
for k,_ in pairs(test) do keys[#keys+1] = k end
table.sort(keys)
local result = {}
local Set = require "pl.Set"
for i=1,#keys-1 do
for j=i+1,#keys do
result[keys[i] .. keys[j]] = Set.values(
Set(test[keys[i]]) + Set(test[keys[j]])
)
end
end