[英]How to make Python do a loop for all items in list at the same time?
我有一個列表,我想同時為列表中的每個項目做一個循環。
我嘗試使用此代碼:
thelist = ['first', 'second', 'third']
def loop():
while True:
for x in thelist:
x = str(x)
time.sleep(5)
do_stuff_that_includes_x()
但它確實通過一個作為排序中一環的東西thelist
。
我想要它做的東西,對所有項目thelist
在同一時間 。
提前致謝。
正如vossad01的注釋所指出的那樣,您的代碼在循環內有5秒的延遲。 這將導致列表中任何兩個項目之間延遲五秒鍾。 如果您取消5秒延遲,您的消息將立即發送到列表中的所有房間。
thelist = ['first', 'second', 'third']
def loop():
while True:
for x in thelist:
x = str(x)
do_stuff_that_includes_x()
time.sleep(5)
我認為您需要多重處理:
import time
def work(x):
x = str(x)
time.sleep(5)
print x
# do_stuff_that_includes_x()
thelist = ['first', 'second', 'third']
from multiprocessing import Pool
p = Pool( len( thelist ) )
p.map( work, thelist )
首先,由於全局解釋器鎖(GIL),多線程並行化不會使性能提高。 因此,如果出於性能原因執行此操作,則需要查看多處理模塊。 看看如何並行化一個簡單的python循環? 有關使用進程池的映射成員完成此操作的示例。
注意:重新分配迭代變量(x)是一種不好的形式。 另外,由於您希望並行執行,因此如果可以在x上設置do_stuff_that_includes_x()參數,將是最簡單的。
使用*
運算符一次解壓縮整個列表
do_stuff_that_includes_x(*x)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.