假设您的问题是对由不同数量的相同字符组成的字符串进行分组,我设法想出了一个名为 agroupTables() 的函数。
功能:
function agroupTables(tableOfTables)
local existentChars = {}
local agroupedItems = {}
for i, currentTable in ipairs(tableOfTables) do
for j, item in ipairs(currentTable) do
local character = string.sub(item, 1, 1) -- get the first character of the current item
if not table.concat(existentChars):find(character) or i == 1 then -- checks if character is already in existentChars
table.insert(existentChars, 1, character)
table.insert(agroupedItems, 1, {item})
else
for v, existentChar in ipairs(existentChars) do
if item :find(existentChar) then -- check in which group the item should be inserted
table.insert(agroupedItems[v], 1, item)
table.sort(agroupedItems[v]) -- sort by the number of characters in the item
end
end
end
end
end
return agroupedItems
end
使用示例
table1 = {'aa','b','c','d','e'}
table2 = {'a','bb','cc','dd','ee'}
table3 = {'aaa','bbb','ccc','ddd','eee', 'z'}
agroupedTables = agroupTables({table1, table2, table3})
for i, v in ipairs(agroupedTables) do
print("group: ".. i .." {")
for k, j in ipairs(v) do
print(" " .. j)
end
print("}")
end
输出:
group: 1 {
z
}
group: 2 {
e
ee
eee
}
group: 3 {
d
dd
ddd
}
group: 4 {
c
cc
ccc
}
group: 5 {
b
bb
bbb
}
group: 6 {
a
aa
aaa
}