我收到以下输入的字符串数据:
"route1,1234,1,no~,,route2,1234,1,no~,"
它代表数据的两个“记录”……每个记录有4个字段。我已经建立了将这个字符串解析为单独的列/字段的代码。但是不起作用的部分是当我测试以查看字段2中是否有重复项时。字段2是当前值为“ 1234”的那个。
这是代码:
function string:split(delimiter)
local result = { }
local from = 1
local delim_from, delim_to = string.find( self, delimiter, from )
while delim_from do
table.insert( result, string.sub( self, from , delim_from-1 ) )
from = delim_to + 1
delim_from, delim_to = string.find( self, delimiter, from )
end
table.insert( result, string.sub( self, from ) )
return result
end
local check_for_duplicate_entries = function(route_data)
local route
local route_detail = {}
local result =true
local errtxt
local duplicate = false
print("received :" ..route_data)
route = string.gsub(route_data, "~,,", "~")
route = route:sub(1,string.len(route)-2)
print("route :" ..route)
-- break up in to an array
route = string.split(route,"~")
for key, value in pairs(route) do
route_detail[key] = string.split(value,",")
end
local list_of_second_column_only = {}
for key,value in pairs(route_detail) do
local temp = value[2]
print(temp .. " - is the value I'm checking for")
if list_of_second_column_only[temp] == nil then
print("i dont think it exists")
list_of_second_column_only[key] = value[2]
print(list_of_second_column_only[key])
else
--found a duplicate.
return true
end
end
return false
end
print(check_for_duplicate_entries("route1,1234,1,no~,,route2,1234,1,no~,"))
我认为我要去的地方是测试:
if list_of_second_column_only[temp] == nil then
我认为我正在检查具有temp值的键,而不是具有temp包含的值的值。但是我不知道如何修复语法。另外,我想知道是否有更有效的方法来做到这一点。我收到的作为输入的“记录”数是动态的/未知的,每条记录中第二列的值也是如此。
谢谢。
编辑1
我试图用作参考的帖子是:在Lua列表中搜索一个项目
在答案中,他们展示了如何通过值测试表中的记录,而不是遍历整个表...
if items["orange"] then
-- do something
end
我在玩耍尝试做类似的事情...
仅创建一个表并减少正则表达式匹配,这应该会更有效率。
在match
确实需要,你只在第二场有兴趣的DUP。
local function check_for_duplicate_entries(route_data)
assert(type(route_data)=="string")
local field_set = {}
for route in route_data:gmatch"([^~]*)~,?,?" do
local field = route:match",([^,]*)"
if field_set[field] then
return true
else
field_set[field] = true
end
end
return false
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句