为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

catspeake 2023-01-04 13:34:50
我的问题有点复杂,但是这个问题可以用一个例子来写得相当笼统:我有一个池列表(pools)需要有一个子列表(children)均匀分布在列表中pools。该children列表已经排序,因此可以安全地假设它可以按pools当前顺序分布在 上。例如,如果我有并且[pool1, pool2]我[child1, child2, child3]希望pool1被分配child1并且将被分配:child3pool2child2pools = ['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 assignmentdistribute(pools, children, print_assignment)预期输出为:child1 assigned to pool1child2 assigned to pool2child3 assigned to pool1期望pools和的数量children可以是任意大小,但是,以下情况始终为真:len(pools) < len(children)。
查看完整描述

3 回答

?
守着一只汪

TA贡献1872条经验 获得超3个赞

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


查看完整回答
反对 回复 2023-01-04
?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

我认为它更具可读性:


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


查看完整回答
反对 回复 2023-01-04
?
子衿沉夜

TA贡献1828条经验 获得超3个赞

你可以这样做:


for elem in children:

    if children.index(elem) % 2 == 0:

        print(f"{elem} to {pools[0]}")

    else:

        print(f"{elem} to {pools[1]}")

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


查看完整回答
反对 回复 2023-01-04
  • 3 回答
  • 0 关注
  • 99 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信