如何在没有外部库的情况下在 Lua 中实现此循环
How do I achieve this loop in Lua without external libraries
我是 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 函数。我如何同时迭代两者。感谢帮助
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
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
我是 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 函数。我如何同时迭代两者。感谢帮助
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
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