我是Lua的新手,所以请耐心地跟我说话。我在Lua中有2个csv字符串
a= '1,2,3,4,5'
代表索引 和
b='this,needs,to,be,matched:with,every,single,row,here:'
行由':'分隔。字符而不是换行符
预期输出
1,this,2,needs,3,to,4,be,5,matched
1,with,2,every,3,single,4,row,5,here
我尝试使用以下代码单独迭代它们
local result= {}
local u = unpack or table.unpack
for values in string.gmatch(values_csv, '([^:]+)') do
local data = {}
for column1,column2 in string.gmatch(values, '([^,]+)'),string.gmatch(keys, '([^,]+)') do
print(column1, column2)
end
end
由于某种原因,第二个总是零。我无法在没有外部库的Lua中找到类似于Python的zip函数。我如何同时迭代这两个。谢谢你的帮助
答案 0 :(得分:2)
Egor的解决方案的变体,以便按照您的要求获得输出:
a = '1,2,3,4,5'
b = 'this,needs,to,be,matched:with,every,single,row,here:'
for line in b:gmatch '[^:]+' do
local idx = a:gmatch '%d+'
local ans = {}
for v in line:gmatch '[^,]+' do
ans[#ans+1] = idx()
ans[#ans+1] = v
end
print(table.concat(ans,','))
end
答案 1 :(得分:1)
local keys = '1,2,3,4,5'
local values_csv = 'this,needs,to,be,matched:with,every,single,row,here:some,values,,are,absent:'
for values in values_csv:gmatch'[^:]+' do
local data = {}
local keys_iter = keys:gmatch'[^,]+'
for value_column in (values..','):gmatch'([^,]*),' do
print(keys_iter(), value_column)
end
end