还有另一种方法可以将列表拆分为大小相等的垃圾箱,然后将剩余的垃圾箱放入第一个垃圾箱? [英] Is there another way to split a list into bins of equal size and put the remainder if any into the first bin?

查看:57
本文介绍了还有另一种方法可以将列表拆分为大小相等的垃圾箱,然后将剩余的垃圾箱放入第一个垃圾箱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个排序列表:

x = list(range(20))

我可以将列表分成相等的大小,然后将其余部分按如下方式放入左侧垃圾箱:

I could split the list into equal sizes and put the remainder into the left bins as such:

def split_qustions_into_levels(questions, num_bins=3):
    num_questions = len(questions)
    equal_size = int(num_questions / num_bins)
    slices = [equal_size] * num_bins
    slices[0] += len(questions) % num_bins
    return [[questions.pop(0) for _ in questions[:s]] for s in slices]

如果我从20个项目的列表中有3个垃圾箱,则应该得到大小为(7,7,6)的列表的输出列表:

If I have 3 bins from the list of 20 items, I should get a output list of list with sizes (7,7,6):

>>> x = list(range(20))
>>> split_qustions_into_levels(x, 3)
[[0, 1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13], [14, 15, 16, 17, 18, 19]]

如果我要从20个项目的列表中选择6个垃圾箱,则应该获取大小为(5,3,3,3,3,3)的列表的输出列表:

If I want 6 bins from the list of 20 items, I should get the output list of list with size (5,3,3,3,3,3):

>>> x = list(range(20))
>>> split_qustions_into_levels(x, 6)
[[0, 1, 2, 3, 4],
 [5, 6, 7],
 [8, 9, 10],
 [11, 12, 13],
 [14, 15, 16],
 [17, 18, 19]]

还有另一种方法可以做到这一点,而无需进行混乱的切片和相等大小的计算,并且无需将每个项目都弹出列表列表?

是否有numpy解决方案?

Is there a numpy solution?

推荐答案

也许array_split()是您想要的.

a = np.arange(20)
np.array_split(a, 6)

这篇关于还有另一种方法可以将列表拆分为大小相等的垃圾箱,然后将剩余的垃圾箱放入第一个垃圾箱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆