[英]Running two for loops with different intervals simultaneously in one function
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b, c = filter_list(a)
b = [1, 3, 4, 5]
c = [2, 6, 7, 8,9]
給定列表a
被該列表的元素的特征過濾(不相關)並放入兩個不同的列表a, b
到 function filter_list
。
def print_all_loop(number_list, repetition, seconds=5):
for x in range(0, repetition):
for i in range(len(number_list)):
print(number_list[i])
sleep(seconds)
上面的 function 采用numbers_list
( b OR c
),打印每個元素,休眠給定數量( seconds
)並重復給定次數( repetition
)。
現在我想制作一個 function 可以獲取兩個列表( b AND c
)並使其睡眠不同的數量。
function 應該循環遍歷(在這種情況下打印所有元素)列表b
和c
但每 1 分鍾循環一次,並且每 15 分鍾c
一次b
b
每 1 分鍾的c
和每 15 分鍾的 c 應該是:
min
1 print b [1, 3, 4, 5] and print c [2, 6, 7, 8, 9]
2 print b
3 print b
4 print b
5 print b
6 print b
7 print b
8 print b
9 print b
10 print b
11 print b
12 print b
13 print b
14 print b
15 print b [1, 3, 4, 5] and print c [2, 6, 7, 8, 9]
16 print b
除了線程,還有其他方法可以有效地做到這一點嗎? 因為我寧願不使用它。
提前致謝。 如果需要更多細節,請詢問。
這個怎么樣:
import asyncio
async def print_all(some_list, times, delay=5):
for _ in range(times):
for item in some_list:
print(item)
await asyncio.sleep(delay)
async def loop_lists(a, b, delay_a, delay_b, times):
await asyncio.gather(
print_all(a, times, delay_a),
print_all(b, times, delay_b)
)
async def main():
a = [1, 3, 4, 5]
b = ["x", "y", "z"]
await loop_lists(a, b, 2, 1, 5)
if __name__ == '__main__':
asyncio.run(main())
asyncio.gather
同時運行傳遞的等待對象。 請注意,要使其正常工作,您必須使用asyncio.sleep
function 而不是time.sleep
function。 這是因為您需要一個事件循環可以切換上下文的點,即停止執行一個協程並跳到另一個協程。
PS:
您甚至可以概括loop_lists
以接受任意數量的列表延遲對,如下所示:
async def loop_lists(*list_delay_pairs, times):
await asyncio.gather(
*(print_all(lst, times, delay) for lst, delay in list_delay_pairs)
)
然后這樣稱呼它:
async def main():
a = [1, 3, 4, 5]
b = ["x", "y", "z"]
await loop_lists((a, 2), (b, 1), times=5)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.