如何从列表中删除重复的字符串值

这是之前一个 问题 的续篇。

我在 Lua 中有一个固定的列表,我正在重新分配值。

local a = {"apple", "pear", "orange", "kiwi", "tomato"}
local map = {
  apple = "RD",
  pear = "GR",
  orange = "OG",
  kiwi = "GR",
  tomato = "RD",
  banana = "YL",
}
colours = {}
for index = 1, #a do
  table.insert(colours,map[a[index]or "OT")
end

现在我要么想编辑现有的脚本,要么添加一些新的脚本,以删除任何重复的值。

最终结果应该是一个没有重复值或空字符串的表(颜色),但我似乎想不出一个简洁的方法来做到这一点!

如果不可能(或真的很混乱),我的第二个选择将是计算表中唯一值的数量。

点赞
用户4070330
用户4070330

解决方案: 给 table 函数添加 contains

table.contains = function(t, value)
    for index = 1, #t do
        if t[index] == value then
            return index
        end
    end
end

因此,仅仅具有唯一颜色的问题可以得到解决:

for index = 1, #a do
    local colour = map[a[index]] or "OT"
    if not table.contains(colours, colour) then
        table.insert(colours, colour)
    end
end

我认为这很整洁。

2019-08-07 14:01:27
用户2858170
用户2858170

如果你不想每次添加元素时都遍历整个表格,可以简单地创建第二个表格来记住已列出的颜色。 只需使用颜色作为键。

local a = {"apple", "pear", "orange", "kiwi", "tomato"}
local map = {
  apple = "RD",
  pear = "GR",
  orange = "OG",
  kiwi = "GR",
  tomato = "RD",
  banana = "YL",
}

local listedColours = {}
local colours = {}
for _,colour in pairs(a) do
  colour = map[colour] or "OT"
  if not listedColours[colour] then
    table.insert(colours, colour)
    listedColors[colour] = true
  end
end
2019-08-07 14:55:03