繁体   English   中英

如何使Python同时对列表中的所有项目执行循环?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM