[[1,2,3], [4,5], [-6ren">
gpt4 book ai didi

python - 将列表拆分为平衡长度的部分

转载 作者:太空狗 更新时间:2023-10-29 21:48:00 24 4
gpt4 key购买 nike

我需要一个算法,它给定一个列表 L 和一个数字 N,返回一个 N 较小列表的列表,其中子列表是 "均衡”。示例:

algo(range(1, 8), 3)  -> [[1,2,3], [4,5], [6,7]]
algo(range(1, 6), 4) -> [[1,2], [3], [4], [5]]
algo(range(1, 12), 5) -> [[1,2,3], [4,5], [6,7], [8,9], [10, 11]]

如您所见,算法应该“优先”输出中的第一个列表。

我已经尝试了几个小时,但我想不出一个漂亮而简洁的算法。顺便说一句,这将在 Python 中实现,但它确实是我在这里追求的算法。这不是家庭作业,这是一个将在三列列表中显示内容的网站 (Django)。


我从 freenode 上的#python 得到了最佳答案,如下所示:

def split_up(l, n):
q, r = divmod(len(l), n)
def division_point(i):
return i * q + min(i, r)
return [l[division_point(i):division_point(i+1)] for i in range(n)]

不过不要问我为什么它有效。 :) 不过,我会为得票最多的人给出正确答案。

最佳答案

这是我想出的代码,没有排序。如果输入未排序,只需轻敲 lst.sort()。

我认为结果很好,使用迭代器并使用 islice 切下下一 block 。

import itertools

def partlst(lst, n):
"""Partition @lst in @n balanced parts, in given order"""
parts, rest = divmod(len(lst), n)
lstiter = iter(lst)
for j in xrange(n):
plen = len(lst)/n + (1 if rest > 0 else 0)
rest -= 1
yield list(itertools.islice(lstiter, plen))

parts = list(partlst(range(1, 15), 5))
print len(parts)
print parts

关于python - 将列表拆分为平衡长度的部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1380162/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com