问题
I've started fiddling a lot with lua recently, but I can't for my life figure this out.
Let's say I have a string that looks like this:
s = "a=x a=y b=z a=x"
I want to remove all duplicates and merge the values of duplicate keys into a table, so that I get:
t = {
a = {x,y},
b = {z},
}
I've been pondering about this for way too long. Any help is appreciated!
回答1:
Try this:
s="a=x a=y b=z a=x"
s=s.." "
t={}
for k,v in s:gmatch("(.-)=(.-)%s+") do
if t[k]==nil then t[k]={} end
t[k][v]=true
end
for k,v in pairs(t) do
for z in pairs(v) do print(k,z) end
end
来源:https://stackoverflow.com/questions/16278657/lua-tables-merge-values-of-duplicate-keys-and-remove-duplicates