python - 如何在Python中并行迭代for循环中的列表
问题描述
我有一个列表,我们可以使用 for 循环进行迭代,如下所示:
myList = ['A', 'B', 'C', 'D']
for elem in myList:
print("Element = %s" % elem)
以上将按顺序迭代列表。但我想同时做到这一点。怎么做?是否可以在不创建任何新方法的情况下这样做?是否有必要创建任何多线程或多处理?
请指教。任何例子都值得赞赏
谢谢。
解决方案
作为对我添加的评论的回应,您可以使用线程来同时执行功能。您需要导入库,定义要同时运行的两个函数,然后创建线程。
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()
推荐阅读
- c# - 如何在 lambda 表达式和布尔类型之间进行转换
- javascript - 我只需要在用户完成输入后调用该函数
- java - 如何在 Java 中对齐数字
- url-parameters - Google 应用程序脚本无法从新 Google 网站上的页面获取 url 参数
- android - Android findView的Linearlayout并在recycleradapter中设置背景
- ios - 以编程方式编码的带有标签栏控制器的双导航栏
- r - 为什么我的 ggplot 中没有包含第二个图例?
- python - 让 pyodbc 在 Cloud Foundry 中连接
- visual-studio-code - 尝试运行 Microsoft Office 加载项调试器时出现 ECONNREFUSED 127.0.0.1:9222
- javascript - 如何在Javascript中按id和日期合并2个对象数组?