I
I
Ivan2020-10-05 19:22:53
Python
Ivan, 2020-10-05 19:22:53

How to process other elements in the for loop while using time.sleep()?

I'm not very friendly with asynchrony, but I need it.
How can I make the for loop process other elements while one is under action time.sleep()?
More or less like this:

for element in list:
    if element == 1:
        pass
    elif element == 2:
        time.sleep(5000)
        list.remove(element)
        #время большое, а нужно чтобы и другие обрабатывались

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vlad Grigoriev, 2020-10-05
@mlneko

Use async, sample code.

import asyncio
from time import time

els = list(range(20))


async def rm_list(v):
    await asyncio.sleep(5)
    print(v)


async def _main():
    await asyncio.gather(*(
        rm_list(value) for value in els
    ))


start = time()
loop = asyncio.get_event_loop()
loop.run_until_complete(_main())
loop.close()
print(time() - start)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question