加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

for-loop – lua中的并行迭代

发布时间:2020-12-14 21:45:50 所属栏目:大数据 来源:网络整理
导读:我想在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中并行遍历多个表.我可以这样做:

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,... )
    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,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,c )
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读