Lua 如何确定一个数组是否是另一个数组的子集?
在Python中,我们可以使用set或itertools来查找另一个列表中一个列表的子集,在Lua中我们如何做同样的事情Lua 如何确定一个数组是否是另一个数组的子集?,lua,moonscript,Lua,Moonscript,在Python中,我们可以使用set或itertools来查找另一个列表中一个列表的子集,在Lua中我们如何做同样的事情 a = {1,2,3} b = {2,3} 如何检查b是否是a的子集?可以在Lua中使用表作为成员资格测试的查找()来实现集合。表中的键是集合的元素,如果元素属于集合,则值为true,否则为nil a = {[1]=true, [2]=true, [3]=true} b = {[2]=true, [3]=true} -- Or create a constructor f
a = {1,2,3}
b = {2,3}
如何检查b是否是a的子集?可以在Lua中使用表作为成员资格测试的查找()来实现集合。表中的键是集合的元素,如果元素属于集合,则值为
true
,否则为nil
a = {[1]=true, [2]=true, [3]=true}
b = {[2]=true, [3]=true}
-- Or create a constructor
function set(list)
local t = {}
for _, item in pairs(list) do
t[item] = true
end
return t
end
a = set{1, 2, 3}
b = set{2, 3}
在这种形式中,编写集合操作也很简单()
如果a
和b
必须保持数组形式,则子集可以这样实现:
function arraysubset(a, b)
local s = set(b)
for _, el in pairs(a) -- changed to iterate over values of the table
if not s[el] then
return false
end
end
return true
end
你能举个例子说明你想要达到的目标吗?
function arraysubset(a, b)
local s = set(b)
for _, el in pairs(a) -- changed to iterate over values of the table
if not s[el] then
return false
end
end
return true
end