我有一个项目数组,每个项目都有一个权重。我想把它分成大小相等,累积重量相等的块。这里有一个答案可以使用numpyhttps://stackoverflow.com/a/33555976/10690958 有没有一种简单的方法可以使用纯python来实现这一点?在
示例数组:
[ ['bob',12],
['jack,6],
['jim',33],
....
]
或者
^{pr2}$这里正确的输出是(假设需要2个块)
[a,11],[b,2] - cumulative weight of 13
以及
[c,5],[d,3],[e,3],[f,2] - cumulative weight of 13
为了进一步澄清这个问题,设想一个将100人分为10部电梯的情况,我们希望每部电梯具有相同的近似总重量(该电梯中所有人的重量总和)。因此,第一个列表将成为名称和权重。这是一个负载平衡问题。在
您只需模仿
cumsum
:构建一个对权重求和的列表。最后你得到了总重量。用累积的权重扫描列表,并在每次达到“块的总重量/数量”时创建一个新的块。代码可以是:你需要这样的分割:
相关问题 更多 >
编程相关推荐