Lua:删除重复的元素 [英] Lua : remove duplicate elements
本文介绍了Lua:删除重复的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在lua中有一张桌子
i am having a table in lua
test = {1,2,4,2,3,4,2,3,4,"A", "B", "A"}
我想删除表中所有重复的元素.
输出应为
I want to remove all duplicate elements in table.
Output should be
test = {1,2,4,3,"A","B"}
我的尝试:
My try :
> items = {1,2,4,2,3,4,2,3,4,"A", "B", "A"}
> flags = {}
> for i=1,table.getn(items) do
if not flags[items[i]] then
io.write(' ' .. items[i])
flags[items[i]] = true
end
>> end
1 2 4 3 A B>
现在工作正常. 感谢您的回答和评论.
It is working fine now. Thanks for answers and comments.
推荐答案
类似于@Dimitry给出的示例,但只有一个循环
Similar to example given by @Dimitry but only one loop
local test = {1,2,4,2,3,4,2,3,4,"A", "B", "A"}
local hash = {}
local res = {}
for _,v in ipairs(test) do
if (not hash[v]) then
res[#res+1] = v -- you could print here instead of saving to result table if you wanted
hash[v] = true
end
end
这篇关于Lua:删除重复的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文