Lua:仅在表中尚未添加或删除重复项时,最明智的添加方式 [英] Lua: Smartest way to add to table only if not already in table, or remove duplicates

查看:45
本文介绍了Lua:仅在表中尚未添加或删除重复项时,最明智的添加方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串表.我想要一种简单的方法来删除表中的所有重复项.

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.

< \ noobquestion>

<\noobquestion>

推荐答案

为此,我通常要做的是在字符串表上建立索引,例如

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 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆