如何同时在两个列表上运行函数?

2024-06-07 16:46:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个简单的问题。从本质上说,我想同时或并行地在一个列表上运行一个函数。你知道吗

这就是我的工作重点

def func(x):
    print(x)
for objectList in space:
    for subObject in objectList:
        func(subObject)

我希望能够同时在每个objectList上运行func()。我知道(实际上我不知道,这就是为什么我要问如何做到这一点)这是线程或并行,但这是我第一次尝试这样做。你知道吗

我的问题是,是否有python中的模块或内置函数或标准方法来完成此任务?你知道吗

如果我在这个网站上违反了一条规则,或者你认为这个问题很愚蠢,或者是重复的,或者其他什么,我也很抱歉。你知道吗


Tags: 模块函数in重点列表fordefspace
2条回答

正如其他人所指出的,使用线程和并行计算应该是有道理的,因为它还需要您执行其他操作,比如输入/负载分配和管理工作线程。当然,有一些图书馆已经建立了这些机制。对于简单的应用程序,您可以使用(穿线。穿线)班级。下面是一个使用线程的简单示例。这段代码将为空间的每个元素创建worker。你知道吗

import threading


def func(x):
    print(x)


class FuncThread(threading.Thread):
    def __init__(self, x):
        threading.Thread.__init__(self)
        self.x = x

    def run(self):
        #worker code = func(x)
        print('doing stuff with:', self.x)


space = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
worker_handlers = list()

for objectList in space:
    for subObject in objectList:
        worker_handlers.append(FuncThread(subObject))

for worker in worker_handlers:
    worker.start()

print('The main program continues to run in foreground.')

for worker in worker_handlers:
    worker.join()  # Wait for the background tasks to finish
print('Main program waited until background was done.')

从python文档:

the Pool object [...] offers a convenient means of parallelizing the execution of a function across multiple input values, distributing the input data across processes (data parallelism)

您可以使用这个模式,它也来自docs

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    with Pool(5) as p:
        print(p.map(f, [1, 2, 3]))

相关问题 更多 >

    热门问题