如何将较大的数组分布在较小的数组上
How to distribute a larger array over a smaller array
我的问题有点复杂,但是这个问题可以用一个例子来写得相当笼统:我有一个池列表(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)
.
您可以使用 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
你可以这样做:
for elem in children:
if children.index(elem) % 2 == 0:
print(f"{elem} to {pools[0]}")
else:
print(f"{elem} to {pools[1]}")
考虑到您只有两个池,如果他的索引是奇数,您可以将 children 分配给 pool1。
这是对 的轻微修改,我认为它更具可读性:
from itertools import cycle
pools = ['pool1', 'pool2']
children = ['child1', 'child2', 'child3']
for child, pool in zip(children, cycle(pools)):
print(f'{child} assigned to {pool}')
输出:
child1 assigned to pool1
child2 assigned to pool2
child3 assigned to pool1
我的问题有点复杂,但是这个问题可以用一个例子来写得相当笼统:我有一个池列表(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)
.
您可以使用 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
你可以这样做:
for elem in children:
if children.index(elem) % 2 == 0:
print(f"{elem} to {pools[0]}")
else:
print(f"{elem} to {pools[1]}")
考虑到您只有两个池,如果他的索引是奇数,您可以将 children 分配给 pool1。
这是对
from itertools import cycle
pools = ['pool1', 'pool2']
children = ['child1', 'child2', 'child3']
for child, pool in zip(children, cycle(pools)):
print(f'{child} assigned to {pool}')
输出:
child1 assigned to pool1
child2 assigned to pool2
child3 assigned to pool1