首页 > 解决方案 > 有没有办法将列表拆分为块?

问题描述

我有一个非常大的列表(~1M 项),我想打开它。
我看到不可能解压超过 8000 个项目的列表,所以我想把它分块。
基本上这个函数在python

def chunks(lst, size):
    for i in range(0, len(lst), size):
         yield lst[i:i+size]

(作为参考,我正在使用 eval 在 redis 上运行 lua 脚本)

标签: lua

解决方案


您可以编写一个迭代器,为您提供一定大小的块。

-- an iterator function that will traverse over lst
function chunks(lst, size)
   -- our current index
   local i = 1
   -- our chunk counter
   local count = 0
   return function()
     -- abort if we reached the end of lst
     if i > #lst then return end
     -- get a slice of lst
     local chunk = table.move(lst, i, i + size -1, 1, {})
     -- next starting index
     i = i + size
     count = count + 1
     return count, chunk
   end
end

-- test
local a = {1,2,3,4,5,6,7,8,9,10,11}
for i, chunk in chunks(a, 2) do
  print(string.format("#%d: %s", i, table.concat(chunk, ",")))
end

输出:

#1: 1,2
#2: 3,4
#3: 5,6
#4: 7,8
#5: 9,10
#6: 11

读这个:

https://www.lua.org/pil/7.1.html

https://www.lua.org/manual/5.4/manual.html#3.3.5


推荐阅读