以下略有改动的版本允许我从多维表格(dictionarry风格)中过滤掉唯一的字段值
[url] http://rosettacode.org/wiki/Remove_duplicate_elements#Lua
items = {1,2,3,4,1,2,3,4,"bird","cat","dog","dog","bird"}`
flags = {}
io.write('Unique items are:')
for i=1,#items do
if not flags[items[i]] then
io.write(' ' .. items[i])
flags[items[i]] = true
end
end
io.write('\n')`
我迷失的是'如果不是......那么......结束'部分确实如此。对我来说,这是愚蠢的,但嘿,它有效;-)现在我想知道引擎盖下发生了什么。
我希望多维不冒犯任何人,我指的是一个由多行组成的表,每行包含多个键值对。
这是我正在使用的代码,没有精彩的改编,但足以过滤字段名称上的唯一值
for i=1,#table,1 do
if not table2[table[i].fieldname] then
table2[table[i].fieldname] = true
end
end
for k,v in pairs(table2) do
print(k)
end
答案 0 :(得分:1)
function findDuplicates(t)
seen = {} --keep record of elements we've seen
duplicated = {} --keep a record of duplicated elements
for i = 1, #t do
element = t[i]
if seen[element] then --check if we've seen the element before
duplicated[element] = true --if we have then it must be a duplicate! add to a table to keep track of this
else
seen[element] = true -- set the element to seen
end
end
return duplicated
end
if seen[element] then
背后的逻辑是,我们检查表格中是否已经看到元素。好像它们的密钥不存在nill
将被返回,其被评估为false(这是不与boolean false
相同,有两种类型的false in LUA!)。
您可以像这样使用此功能:
t = {'a','b','a','c','c','c','d'}
for key,_ in pairs(findDuplicates(t)) do
print(key)
end
然而,该函数不适用于多维表,但是这个表将会:
function findDuplicates(t)
seen = {} --keep record of elements we've seen
duplicated = {} --keep a record of duplicated elements
local function traverse(subt)
for i=1, #subt do
element = subt[i]
if type(element) == 'table' then
traverse(element)
else
if seen[element] then
duplicated[element] = true
else
seen[element] = true
end
end
end
end
traverse(t)
return duplicated
end
示例用法:
t = {'a',{'b','a'},'c',{'c',{'c'}},'d'}
for k,_ in pairs(findDuplicates(t)) do
print(k)
end
输出
a
c
t = {a='a',b='b',c='c',d='c',e='a',f='d'}
function findDuplicates(t)
seen = {}
duplicated = {}
for key,val in pairs(t) do
if seen[val] then
duplicated[val] = true
else
seen[val] = true
end
end
return duplicated
end
这与以前的工作方式相同,但检查相同的值是否与不同的键相关联,如果是,则将该值记录为重复。< / p>
答案 1 :(得分:0)
最终这是对我有用的代码。我被要求将其作为一个单独的答案发布,所以这里就是。
for i=1,#table1,1 do
if not table2[table1[i].fieldname] then
table2[table1[i].fieldname] = true
end
end
for k,v in pairs(table2) do
print(k)
end