将字符串重新分配给数组中一组值的列表 [英] Reassigning strings to a set list of values in an array

查看:79
本文介绍了将字符串重新分配给数组中一组值的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个固定格式的Lua列表(这是来自其他位置的输入).

I have a list in Lua which is fixed format (it's an input from somewhere else).

例如

a = {"apple", "apple 1", "pear", "orange", "orange 3", "kiwi", "tomato"}

我也有一个查找表,我想在其中标准化该集合并将其发送为代码格式.注意:任何包含Apple的东西,例如apple 1,apple 2等,都将被映射为与apple相同的值.

I also have a look up table where I want to normalise this set and send them to a code format. Note: anything containing apple, such as apple 1, apple 2 etc will be mapped to the same value as apple.

例如

"apple" => "RD"
"pear" => "GR"
"orange" => "OG"
"kiwi" => "GR"
"tomato" => "RD"
"banana" => "YL"
etc...

然后我想返回一个包含所有这些替换的列表:

I then want to return a list with all of these substitutions:

fruitBox = {"RD", "GR", "OG"}

我不介意fruitBox是否具有重复的值,最简单的方法是,但它仅在同时在查找和原始列表中表示的情况下才返回值.我一直在尝试这样做,但是要匹配字符串,但是我总是最终陷入如何输出代码的困境.我也尝试过string.gsub并遍历for loop,但仍然没有用处.

I don't mind if fruitBox has repeated values or not, whatever is easiest, but it should only return values if they are represented in both the lookup and the original list. I have been trying to do this but matching the strings, but I always end up getting stuck with how to output the codes. I also tried string.gsub and iterating through a for loop but still got nowhere useful.

推荐答案

您需要将映射列表存储在(哈希表)中,并遍历第一个列表,使用第二个表中的映射更改元素.这样的事情应该起作用:

You need to store the list of mappings in a (hash) table and iterate over the first list changing the elements using the mapping from the second table. Something like this should work:

local a = {"apple", "pear", "orange", "kiwi", "tomato"}
local map = {
  apple = "RD",
  pear = "GR",
  orange = "OG",
  kiwi = "GR",
  tomato = "RD",
  banana = "YL",
}
for index = 1, #a do
  a[index] = map[a[index]] or "missing mapping"
end

-- print results
for index = 1, #a do print(a[index]) end

这会为我打印RD GR OG GR RD.

如果您真的想跳过映射中不存在的元素(我不建议这样做,因为在映射或数据中很难发现错误),请使用分离表并在循环中执行table.insert而不是a[index]...分配.

If you really want to skip the elements not present in the mapping (which I don't recommend, as it will be difficult to find errors in the mapping or the data), then use a separate table and do table.insert instead of a[index]... assignment in the loop.

如果字符串中包含一些非字母(如更新的问题中所述),则您可能需要使用gsub("%A","")或类似的方式将其删除.

If the strings have some non-letters (as in the updated question), you may want to remove them using gsub("%A","") or something similar.

这篇关于将字符串重新分配给数组中一组值的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆