首页 > 解决方案 > 如何将较大的数组分布在较小的数组上

问题描述

我的问题涉及更多的复杂性,但问题可以用一个例子来写得相当笼统:我有一个池列表(pools),需要一个子列表(children)均匀分布在pools.

children列表已经排序,因此可以安全地假设它可以按pools当前顺序分布在 中。

例如,如果我有[pool1, pool2]并且[child1, child2, child3]我希望pool1被分配child1并且child3并且pool2会被分配child2

pools = ['pool1', 'pool2']
children = ['child1', 'child2', 'child3']

def print_assignment(pool, child)
  print('{} assigned to {}'.format(child, pool)

# The expectation is that distribute would perform the core logic and 
# call print_assignment during each assignment
distribute(pools, children, print_assignment)

预期输出为:

child1 assigned to pool1
child2 assigned to pool2
child3 assigned to pool1

期望是 和 的计数pools可以children是任意大小,但是,以下情况总是正确的:len(pools) < len(children).

标签: pythonalgorithmround-robin

解决方案


您可以itertools.cycle用于任务:

from itertools import cycle

pools = ['pool1', 'pool2']
children = ['child1', 'child2', 'child3']

c = cycle(pools)
for child in children:
    print('{} assigned to {}'.format(child, next(c)))

印刷:

child1 assigned to pool1
child2 assigned to pool2
child3 assigned to pool1

推荐阅读