我正在尝试创建一个客户端-服务器应用程序,在该应用程序中,客户端注册请求,并在稍后获得响应。
对于快速插入,我使用defaultdict。
{
"john": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
"ram": [2, 6],
"bruce": [1, 4, 5],
"willam": [7, 1],
}所以我想圆角可能会来拯救我,给我一个迭代器来产生像这样的客户端-
"john", 0
"ram", 2
"bruce", 1
"willam", 7
"john", 1
"ram", 6
"bruce", 4
... 有谁能告诉我怎样才能高效地实现这样的迭代器?
编辑:这是我想出来的。有没有人有更好的方法来做事情?
def roundrobin(requests):
remaining = set(requests)
index = 0
while remaining:
up_next = set()
for key in remaining:
try:
print(key, requests[key][index])
except IndexError:
continue
up_next.add(key)
remaining = up_next
index += 1 它会产生以下输出
ram 2
john 0
willam 7
bruce 1
bruce 4
ram 6
john 1
willam 1
john 2
bruce 5
john 3
john 4
john 5
john 6
john 7
john 8
john 9
john 10
john 11
john 12
john 13
john 14
john 15
john 16
john 17
john 18
john 19发布于 2018-11-25 05:34:40
我认为没有比这更好的了。
def roundrobin2(requests):
index = 0
while requests:
for key in list(requests):
try:
key, requests[key][index]
except IndexError:
del requests[key]
else:
index += 1发布于 2018-11-25 05:43:08
您可以为每个请求者创建一个存储桶,并使用itertools.cycle循环遍历,每次都会弹出。
import itertools
all_requests = {
"john": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
"ram": [2, 6],
"bruce": [1, 4, 5],
"willam": [7, 1],
}
# handle requests:
for requester in itertools.cycle(all_requests):
request, all_requests[requester] = all_requests[requester][0], all_requests[requester][1:]
# Intuitively this seems faster than request = all_requests[requester].pop(0), but I could be wrong
# you should profile this before using it in production code, or see my note below.
response = handle_request(request)
send_response(response)请注意,我经常从这个列表的头部拉出,所以你可能应该使用collections.deque,它有快速的弹出和从头部或尾部推送。
https://stackoverflow.com/questions/53462299
复制相似问题