【问题标题】:Is there another way to split a list into bins of equal size and put the remainder if any into the first bin?是否有另一种方法将列表拆分为相同大小的箱并将剩余部分(如果有)放入第一个箱中?
【发布时间】:2018-02-21 05:46:28
【问题描述】:

给定一个排序列表:

x = list(range(20))

我可以将列表分成相等的大小,然后将剩余的放入左侧的 bin 中:

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) 的列表的输出列表:

>>> 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 个 bin,我应该得到大小为 (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 解决方案吗?

【问题讨论】:

  • 4 + 3 + 3 + 3 +3 != 20
  • 哎呀错字! ;P

标签: python list numpy split binning


【解决方案1】:

也许array_split() 就是你想要的。

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

【讨论】:

  • (4,4,3,3,3,3)array_split() 拆分要好得多!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-31
  • 2016-07-22
  • 1970-01-01
  • 1970-01-01
  • 2018-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多