Lua:仅在表中未添加或删除重复项时才添加到表的最聪明方法 [英] Lua: Smartest way to add to table only if not already in table, or remove duplicates
问题描述
我有一个字符串表.我想要一种简单的方法来删除表格的所有重复项.
I have a table of strings. I'd like an easy way to remove all of the duplicates of the table.
所以如果表是 {a, b, c, c, d, e, e}
,在这个操作之后它会是 {a, b, c, d, e}
So if the table is {a, b, c, c, d, e, e}
, after this operation it would be {a, b, c, d, e}
或者,可能最好是有一种方法可以将元素添加到表格中,但前提是该元素尚未包含在表格中.
Alternatively, and probably preferably, is there a way to add an element to a table, but only if it is not already contained within the table.
< oobquestion>
< oobquestion>
推荐答案
我通常为此做的是在字符串上索引表格,例如
What I normally do for this is index the table on the string so for example
tbl[mystring1] = 1
tbl[mystring2] = 1
等
当您添加字符串时,您只需使用上面的行,重复项将被处理.然后您可以使用 for ... 对 do 循环来读取数据.
When you add a string you simply use the lines above and duplicates will be taken care of. You can then use a for ... pairs do loop to read the data.
如果你想统计出现的次数
If you want to count the number of occurrences
使用类似
if tbl[mystring1] == nil then
tbl[mystring1] = 1
else
tbl[mystring1] = tbl[mystring1] + 1
end
作为加法循环的结束,如果你需要扭转局面,你可以简单地使用类似的东西
As the end of the addition cycle if you need to turn the table around you can simply use something like
newtbl = {}
for s,c in pairs(tbl) do
table.insert(newtbl,s)
end
这篇关于Lua:仅在表中未添加或删除重复项时才添加到表的最聪明方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!