如何将较大的数组分布在较小的数组上

我的问题有点复杂,但是这个问题可以用一个例子来写得相当笼统:我有一个池列表(pools)需要有一个子列表(children)均匀分布在列表中pools。


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


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


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)。


catspeake
浏览 100回答 3
3回答

守着一只汪

from itertools import cyclepools = ['pool1', 'pool2']children = ['child1', 'child2', 'child3']c = cycle(pools)for child in children:    print('{} assigned to {}'.format(child, next(c)))印刷:child1 assigned to pool1child2 assigned to pool2child3 assigned to pool1

潇潇雨雨

我认为它更具可读性:from itertools import cyclepools = ['pool1', 'pool2']children = ['child1', 'child2', 'child3']for child, pool in zip(children, cycle(pools)):    print(f'{child} assigned to {pool}')输出:child1 assigned to pool1child2 assigned to pool2child3 assigned to pool1

子衿沉夜

你可以这样做:for elem in children:&nbsp; &nbsp; if children.index(elem) % 2 == 0:&nbsp; &nbsp; &nbsp; &nbsp; print(f"{elem} to {pools[0]}")&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; print(f"{elem} to {pools[1]}")考虑到你只有两个池,如果他的索引是奇数,你可以将孩子分配给 pool1。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python