Lua, Tables: merge values of duplicate keys and remove duplicates

强颜欢笑 提交于 2019-12-11 03:25:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!