简体   繁体   English

Memory 创建批处理并将功能应用于 python 列表的高效且最快的方法

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

I need to create batch of 5 and apply function on each value of the list in memory efficient and fastest way.我需要创建 5 个批次,并在 memory 中的列表的每个值上应用 function 高效和最快的方式。 I need to avoid two steps to do the batching.我需要避免两个步骤来进行批处理。 I need to do it in a single step in most efficient and fatest way.我需要以最有效和最快的方式一步完成。 Please help in doing it in a efficient way.请帮助以有效的方式进行操作。

Sample code:示例代码:

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)

Results:结果:

[{'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'}]

If you're having memory issues, you can try to maintain everything as an iterator until the last possible moment.如果您遇到 memory 问题,您可以尝试将所有内容保持为迭代器,直到最后一刻。 Then you can iterate over each item one at a time, or call list(records) if you want to try to make a final list:然后,您可以一次遍历每个项目,或者如果您想尝试制作最终列表,请调用list(records)

(I removed the json and uuid to make the structure clearer): (我删除了 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)

Prints:印刷:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Pandas中从列值创建排序列表的高效最快方法 - Efficient and fastest way in Pandas to create sorted list from column values Python:创建一个包含 n 个列表的列表的最快方法 - Python: fastest way to create a list of n lists 在Python中创建词典列表的最有效方法 - Most efficient way to create a list of dictionaries in Python 搜索字符串列表的高效且最快捷的方式 - Efficient and fastest way to search in a list of strings Python - 从带有计算的列表中创建元组的最快方法 - Python - Fastest way to create a tuple from a list with computations 以最快的方式从 dataframe Python 中的索引创建一个新的字典列表 - Create a new list of dictionary from the index in dataframe Python with the fastest way Python 字典,多个键指向 memory 有效方式中的同一列表 - Python dictionary with multiple keys pointing to same list in memory efficient way 从Python中的字符串创建重叠子串列表的最快方法 - Fastest way to create a list of overlapping substrings from a string in Python 功能列表中的Python For循环 - Python For Loop in List with fuction 在 Python 中迭代列表并找到合适的字符串模式的最快(最有效)方法是什么? - What's the fastest (most efficient) way to iterate through a list and find a fitting string pattern in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM