【问题标题】:I want to collect the table elements and create a new table. (lua)我想收集表格元素并创建一个新表格。 (卢阿)
【发布时间】:2021-08-21 19:36:29
【问题描述】:

我找不到类似的案例。请帮忙! (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',...}

【问题讨论】:

    标签: lua redefinition


    【解决方案1】:

    假设您的问题是对由不同数量的相同字符组成的字符串进行分组,我设法想出了一个名为 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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-18
      • 1970-01-01
      • 1970-01-01
      • 2020-05-25
      • 2021-10-20
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      相关资源
      最近更新 更多