lua - 从 Lua 中的表中获取所有重复项

标签 lua lua-table

我需要一点帮助 假设我有一个包含数字的表格。

tbl = {'item1' = 6, 'item2' = 1, 'item3' = 6, 'item4' = 3, 'item5' = 2, 'item5' = 3}

我想把所有重复的数字放在同一个表中(带有键和值),如下所示:

repeated = {'item1' = 6, 'item3' = 6, 'item4' = 3, 'item5' = 3}

并用“不重复”的数字创建一个新的:

notrepeated = {'item2' = 1, 'item5' = 2}

有人可以帮忙吗?非常感谢。

最佳答案

-- Count the items for each number
local itemsByNum = {}
for item, num in pairs(tbl) do
    itemsByNum[num] = (itemsByNum[num] or 0) + 1
end
-- Now move objects to the respective tables
local rep, noRep = {}, {} -- can't use "repeat" as that's a Lua keyword
for item, num in pairs(tbl) do
    if itemsByNum[num] > 1 then -- repeated at least once
        rep[item] = num
    else -- unique number
        norep[item] = num
    end
end

关于lua - 从 Lua 中的表中获取所有重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72805970/

相关文章:

非英文字符的 string.sub 问题

lua - Lua新手——表操作

variables - 包含另一个变量值的变量名

lua - table.insert 覆盖现有索引

if-statement - 什么是更快?一个循环或多个 if 条件

function - Lua 中退出和重新启动函数

string - 为什么我们可以做 str :split (",") but not tab:insert(val)?

lua - 在 Lua 中重新定义变量的类型

loops - 操作 Lua 表时遇到问题

string - 将表解析为字符串后 -> 反转(将字符串解析为表)