收集表格元素并创建一个新表(lua)

我找不到类似的案例。请帮我!(lua)

输入 :

table1={'a','b','c','d','e'}
table2={'aa','bb','cc','dd','ee'}
table3={'aaa','bbb','ccc','ddc','eee'}
...

输出 :

group1={'a','aa','aaa',...}
group2={'b','bb','bbb',...}
group3={'c','cc','ccc',...}
group4={'d','dd','ddd',...}
group5={'e','ee','eee',...}
点赞
用户16701376
用户16701376

假设你的问题是将由不同数量的相同字符组成的字符串分组,我成功地编写了一个名为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) -- 获取当前项的第一个字符

      if not table.concat(existentChars):find(character) or i == 1 then -- 检查字符是否已经存在于existentChars中
        table.insert(existentChars, 1, character)
        table.insert(agroupedItems, 1, {item})
      else
        for v, existentChar in ipairs(existentChars) do
          if item :find(existentChar) then -- 检查应该将项插入到哪个组中
            table.insert(agroupedItems[v], 1, item)
            table.sort(agroupedItems[v]) -- 根据项中字符的数量排序
          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
}
2021-08-22 20:07:39