创建批次并将函数应用于 python 列表的内存高效且最快的方法

Memory efficient and fastest way to create batchs and applying fuction to python list

我需要创建 5 个批次并在内存高效且高效的列表的每个值上应用函数 最快的方式。我需要避免两个步骤来进行批处理。我需要以最有效和最快的方式一步完成。请帮助以有效的方式进行。

示例代码:

import json
from uuid import uuid4

rows = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

rowlist = [r*r for r in rows]

records = [{'Data': json.dumps(rowlist[i:i + 5]), 'PartitionKey': str(uuid4())} for i in range(0, len(rowlist), 5)]

print(records)

结果:

[{'Data': '[1, 4, 9, 16, 25]', 'PartitionKey': '73ba1cba-248c-4b26-982e-1d902627bfe6'}, {'Data': '[36, 49, 64, 81, 100]', 'PartitionKey': '02a986bf-0495-4620-a3d4-0f0b91cd24d6'}, {'Data': '[121, 144, 169, 196, 225]', 'PartitionKey': 'a0ef674e-95f3-4cb0-8e0b-ad052f7726bf'}]

如果您遇到内存问题,您可以尝试将所有内容都作为迭代器维护,直到最后一刻。然后您可以一次遍历每个项目,或者如果您想尝试制作最终列表,请调用 list(records)

(我删除了json和uuid以使结构更清晰):

rows = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

sqr = lambda r: r*r

records = ({'Data': group} for group in zip(*[map(sqr,rows)] * 5))

for record in records:
    print(record)

打印:

{'Data': (1, 4, 9, 16, 25)}
{'Data': (36, 49, 64, 81, 100)}
{'Data': (121, 144, 169, 196, 225)}