Python 如何批量应用映射操作?

Python 如何批量应用映射操作?,python,python-3.x,data-structures,iteration,list-comprehension,Python,Python 3.x,Data Structures,Iteration,List Comprehension,我使用的函数将对象应用于字符串列表。但是,这需要很多时间才能完成,因为在检查对象的库网站后,作者说您需要分块应用它,以避免内存过载。我正在应用以下功能: list_1 =['hi how are you', 'i am good', ..., 'how is'] results = list( map(lambda string_list_elem: foo(string_list_elem, library_obj), list_1)) 以上所述花费的时间太多。加速函数应用程序的最佳

我使用的函数将对象应用于字符串列表。但是,这需要很多时间才能完成,因为在检查对象的库网站后,作者说您需要分块应用它,以避免内存过载。我正在应用以下功能:

list_1 =['hi how are you', 'i am good', ..., 'how is']
results = list(
    map(lambda string_list_elem: foo(string_list_elem, library_obj), list_1))
以上所述花费的时间太多。加速函数应用程序的最佳方法是什么?到目前为止,我尝试将列表分为以下几部分:

import itertools

def split_seq(iterable, size):
    it = iter(iterable)
    item = list(itertools.islice(it, size))
    while item:
        yield item
        item = list(itertools.islice(it, size))

list(split_seq(list_1, 500))

不过,我不知道这是否有效。我应该做一个列表理解还是仅仅使用这个函数和拆分?加快结果列表过程的推荐方法是什么?

因为您无法显示/共享关键功能/worker
foo()
我无法识别所有需要使用不同优化技术解决的潜在瓶颈。
在这个阶段,我建议通过以下方式从并发/异步方法开始:

从concurrent.futures导入ThreadPoolExecutor
导入功能工具
def foo(字符串列表元素、库对象):
....
str_list=[“你好”,“我很好”,“你好吗”]
使用ThreadPoolExecutor()作为执行器:
#将``替换为实际的库对象
结果=列表(executor.map(functools.partial(foo,library\u obj=),str\u list))
打印(结果)

这将大大加快处理速度。

我试图了解问题是代码太慢,还是由于服务器无法过载而导致服务流量过大。在后一种情况下,问题似乎是固有的,无法解决。在前一种情况下,您可以执行此任务?问题不在于流量,而是在本地执行。问题是我必须逐块应用字符串,然后重新连接它们。但是,我不知道哪种方法是正确的。有很多因素需要依赖:1)列表1的大小是多少?2)
foo
函数在做什么?3) 网络连接速度是多少?4) 需要多少-多少钱以及什么时间可以接受?@anon,发布单个
foo('hi how you',library\u obj)
调用的执行时间-以获得大致的标称值time@anon,对文件的读/写不是联网,而是导致I/O
from concurrent.futures import ThreadPoolExecutor
import functools

def foo(string_list_elem, library_obj):
    ....

str_list = ['hi how are you', 'i am good', ..., 'how is']

with ThreadPoolExecutor() as executor:
    # replace `<your_lib>` with your actual library_obj
    results = list(executor.map(functools.partial(foo, library_obj=<your_lib>), str_list))
    print(results)