机制说明
next_endpoint 读取 endpoints[0] 后调用 rotate(-1),一步把选中的队首转去队尾。六轮打印 api-1、api-2、api-3 两遍——固定列表变成公平的轮询器,无需任何重排代码。
六次选取(3 的倍数)后列表顺序复原,cycle restored 打印 True;rotate(1) 反向转一格,列表向另一侧移动一步。
注意事项
- rotate 是 O(k) 的原地操作,不重建 deque。
- 负数向左转;正数向右转。
核心语句
endpoints.rotate(-1)
代码示例
from collections import deque
endpoints = deque(["api-1", "api-2", "api-3"])
def next_endpoint() -> str:
# Round-robin pick: read the head, then rotate one step left so it queues at the tail
chosen = endpoints[0]
endpoints.rotate(-1)
return chosen
for turn in range(6):
print(f"turn {turn}: {next_endpoint()}")
# After 6 picks (a multiple of 3) the order is restored; rotate(1) turns the other way
print("cycle restored:", list(endpoints) == ["api-1", "api-2", "api-3"])
endpoints.rotate(1)
print("after rotate(1):", list(endpoints))