高效、快速地创建批处理并将fuction应用到python列表中。

问题描述 投票:0回答:1

我需要创建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'}]
python list generator iterable
1个回答
1
投票

如果你有内存问题,你可以尝试把所有的东西都保持为迭代器,直到最后一刻。然后你可以一次一个地迭代每个项目,或者调用 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)}
© www.soinside.com 2019 - 2024. All rights reserved.