lua - 有没有办法将列表拆分为块?
问题描述
我有一个非常大的列表(~1M 项),我想打开它。
我看到不可能解压超过 8000 个项目的列表,所以我想把它分块。
基本上这个函数在python
def chunks(lst, size):
for i in range(0, len(lst), size):
yield lst[i:i+size]
(作为参考,我正在使用 eval 在 redis 上运行 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
读这个:
推荐阅读
- javascript - Aurelia 在 HTML 文件中构建捆绑位置
- laravel - 如何获取通过 response.body 检索的数据数量?
- javascript - 如何配置 websocket?
- sql - 哪条记录导致 SQL 中的合并命令中的错误?
- python - 如何从 Python 打开 Excel 应用程序?
- android - 如何从一个简单的谷歌地图地址搜索中获取价值,并在 Flutter 中自动完成并在 TextFormField 中显示预测
- python - 如何创建像触发事件一样使用先前行的 Pandas 数据框?
- python-3.x - 谷歌语音到文本 api 因多处理 python 而失败
- python - 为每个 epoch 的 tensorflow 时间序列添加验证损失
- node.js - Lambda:node.js 不等到承诺返回