Python 如何在较小的阵列上分布较大的阵列

Python 如何在较小的阵列上分布较大的阵列,python,algorithm,round-robin,Python,Algorithm,Round Robin,我的问题有点复杂,但这个问题可以用一个例子来概括:我有一个池列表,需要在池列表中均匀分布一个子池列表 子列表已经排序,因此可以安全地假设它可以按当前顺序分布在池中 例如,如果我有[pool1,pool2]和[child1,child2,child3],我希望pool1分配给child1,而child3和pool2分配给child2: pools=['pool1','pool2'] children=['child1','child2','child3'] def打印分配池,子 打印分配给{}的{

我的问题有点复杂,但这个问题可以用一个例子来概括:我有一个池列表,需要在池列表中均匀分布一个子池列表

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

例如,如果我有[pool1,pool2]和[child1,child2,child3],我希望pool1分配给child1,而child3和pool2分配给child2:

pools=['pool1','pool2'] children=['child1','child2','child3'] def打印分配池,子 打印分配给{}的{}。格式化子对象,池 预期distribute将执行核心逻辑和 在每次分配期间调用print_分配 分发工具、子项、打印分配 预期输出为:

child1 assigned to pool1
child2 assigned to pool2
child3 assigned to pool1
我们期望池和子池的计数可以是任意大小,但以下情况始终正确:lenpools您可以用于此任务:

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
您可以为任务使用:

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

你可以这样做:

for elem in children:
    if children.index(elem) % 2 == 0:
        print(f"{elem} to {pools[0]}")
    else:
        print(f"{elem} to {pools[1]}")

考虑到您只有两个池,如果子池的索引是奇数,您可以将其分配给池1。

您可以这样做:

for elem in children:
    if children.index(elem) % 2 == 0:
        print(f"{elem} to {pools[0]}")
    else:
        print(f"{elem} to {pools[1]}")

考虑到您只有两个池,如果pool1的索引是奇数,您可以将子项分配给pool1。

这是一个轻微的修改,我认为它更具可读性:

从itertools导入周期 pools=['pool1','pool2'] children=['child1','child2','child3'] 对于儿童,zipchildren中的游泳池,cyclepools: printf'{child}分配给{pool}' 产出:

分配给池1的child1 分配给池2的child2 分配给池1的孩子3
这是一个轻微的修改,我认为它更具可读性:

从itertools导入周期 pools=['pool1','pool2'] children=['child1','child2','child3'] 对于儿童,zipchildren中的游泳池,cyclepools: printf'{child}分配给{pool}' 产出:

分配给池1的child1 分配给池2的child2 分配给池1的孩子3
这仅适用于两个池。Andrej Kesely的答案适用于任何数量的池。这就是为什么我指定它适用于两个池。这只适用于两个池。Andrej Kesely的答案适用于任何数量的池。这就是为什么我指定它适用于两个池。