我想在Lua中并行遍历多个表.我可以这样做: for i in range(#table1) pprint(table1[i]) pprint(table2[i])end 但我宁愿像python的zip: for elem1, elem2 in zip(table1, table2): pprint(elem1) pprint(elem2)end 在标准的Lua中
for i in range(#table1) pprint(table1[i]) pprint(table2[i]) end
但我宁愿像python的zip:
for elem1, elem2 in zip(table1, table2): pprint(elem1) pprint(elem2) end
在标准的Lua中是否有这样的东西(或者至少在火炬包装的任何东西中?).
如果你想在Lua中使用类似于Python函数的东西,你应该首先看一下 Penlight.对于这种特定情况,有seq.zip
功能.它是
seems,Penlight与Torch一起安装,但你也可以通过LuaRocks(它再次与至少一个Torch发行版捆绑在一起)获得它.
无论如何,Penlight中的seq.zip函数仅支持压缩两个序列.这个版本应该更像Python的zip,即允许比两个序列更多(或更少):
local zip do local unpack = table.unpack or unpack local function zip_select( i, var1, ... ) if var1 then return var1, select( i, var1, ... ) end end function zip( ... ) local iterators = { n=select( '#', ... ), ... } for i = 1, iterators.n do assert( type( iterators[i] ) == "table", "you have to wrap the iterators in a table" ) if type( iterators[i][1] ) ~= "number" then table.insert( iterators[i], 1, -1 ) end end return function() local results = {} for i = 1, iterators.n do local it = iterators[i] it[4], results[i] = zip_select( it[1], it[2]( it[3], it[4] ) ) if it[4] == nil then return nil end end return unpack( results, 1, iterators.n ) end end end -- example code (assumes that this file is called "zip.lua"): local t1 = { 2, 4, 6, 8, 10, 12, 14 } local t2 = { "a", "b", "c", "d", "e", "f" } for a, b, c in zip( {ipairs( t1 )}, {ipairs( t2 )}, {io.lines"zip.lua"} ) do print( a, b, c ) end