Skip to main content
 首页 » 编程设计

python之如何让 Python 同时对列表中的所有项目进行循环

2025年05月04日11pengyingh

我有一个列表,我正在尝试为列表中的每个项目做一个循环,同时进行。

我试过使用这段代码:

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)