Lua中在“for循环”和/或“while循环”中计数特定变量的出现次数并识别它们的索引

我正在尝试找出某个变量在for或while循环中出现的次数,然后将它们绑定到正确的索引(i)上。我将使用字母来举例说明我尝试过的内容。

例如:“Letterlist(index)”在每个索引上都包含随机字母从a-z。我想查看循环中字母b出现的次数。

for i = 110 do
  B_LetterCount = 0
  letter = Letterlist(i)
  if letter == b then
    B_LetterID = i
    B_LetterCount = B_LetterCount + 1
  end
end

正如你可能已经注意到的那样,那个循环不起作用,因为字母B的最新出现将覆盖任何其他出现的ID。例如,如果:

1 = a
2 = b
3 = h
4 = b
5 = y
6 = t
7 = a
8 = b
9 = e
10 = k

那么b出现在索引2、4和8上。有没有一种方法可以计数它们并为它们设置ID变量,就像我的例子loop: B_LetterID = i、B_LetterID2 = i等等。 任何帮助都将不胜感激。

点赞
用户2858170
用户2858170
local list = {"a", "b", "h", "b", "y", "t", "a", "b", "e", "k"}

local indices = {}
local counts = {}
for i,v in ipairs(list) do
  indices[v] = indices[v] or {}
  table.insert(indices[v], i)
  counts[v] = counts[v] and (counts[v] + 1) or 1
end

for k,v in pairs(counts) do
  print(string.format("%d %q at:", v, k))
  print(table.unpack(indices[k]))
end

我会留给你去改变代码以适应你的需求。你应该能理解这个代码。

2020-04-24 08:52:59