首页 > 解决方案 > 如何在Python中并行迭代for循环中的列表

问题描述

我有一个列表,我们可以使用 for 循环进行迭代,如下所示:

myList = ['A', 'B', 'C', 'D']
for elem in myList:
    print("Element = %s" % elem)

以上将按顺序迭代列表。但我想同时做到这一点。怎么做?是否可以在不创建任何新方法的情况下这样做?是否有必要创建任何多线程或多处理?

请指教。任何例子都值得赞赏

谢谢。

标签: pythonfor-loop

解决方案


作为对我添加的评论的回应,您可以使用线程来同时执行功能。您需要导入库,定义要同时运行的两个函数,然后创建线程。

import threading

def func1():
    #Perform one action here
    myList = ['A', 'B', 'C', 'D']
    for elem in myList:
        print("Element = %s" % elem)

def func2():
    #Perform one action here
    myList = ['E', 'F', 'G', 'H']
    for elem in myList:
        print("Element = %s" % elem)

t1 = threading.Thread(target=func1) #Create first thread running the function func1
t2 = threading.Thread(target=func2) #Create second thread running the function func2

#Start the threads
t1.start()
t2.start()

推荐阅读