python - 如何将较大的数组分布在较小的数组上
问题描述
我的问题涉及更多的复杂性,但问题可以用一个例子来写得相当笼统:我有一个池列表(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
推荐阅读
- arduino - 将 USB 电缆插入笔记本电脑时未检测到 COM 端口
- ios - Siri Shortcut 的 continueUserActivity 中的 userInfo 为空
- r - pnorm 函数错误信息(使用 Mac OS)(R 版本为 3.5.2)
- tree - 我对二叉树有点困惑
- mysql - 使用 python mysql.connector 模块在 MySql 中索引占位符
- selenium - 如何从 Robot Framework 的输入字段中获取文本?
- powerbi - 在 power bi 中设置切片器的默认值
- flutter - Flutter 自定义 TabBar 指示器
- android - Android Camera2 预览被拉伸
- javascript - VueJs +ElementUi Change 方法没有事件数据