【发布时间】:2011-02-09 05:38:18
【问题描述】:
我正在寻找一种快速、干净、pythonic 的方法来将列表划分为 n 个几乎相等的分区。
partition([1,2,3,4,5],5)->[[1],[2],[3],[4],[5]]
partition([1,2,3,4,5],2)->[[1,2],[3,4,5]] (or [[1,2,3],[4,5]])
partition([1,2,3,4,5],3)->[[1,2],[3,4],[5]] (there are other ways to slice this one too)
这里有几个答案Iteration over list slices 非常接近我想要的,除了他们关注列表的size,我关心number em> 列表(其中一些也用 None 填充)。显然,这些转换很简单,但我正在寻找最佳实践。
同样,人们在How do you split a list into evenly sized chunks? 为一个非常相似的问题指出了很好的解决方案,但我更感兴趣的是分区的数量而不是具体的大小,只要它在 1 以内。同样,这很容易转换,但我正在寻找最佳做法。
【问题讨论】: