分割子列表
2015-02-03 · Mathematica
Mathematica 中按条件或按长度分割列表的两种常见需求。
按条件分割
给定列表和阈值(如 50),要求每段子列表的累加和不超过该阈值。可用 TakeWhile[Accumulate@list, # < 50 &] 确定每段长度,配合 Reap/Sow 与 FixedPointList 反复分割,直到余下为空。
按长度列表分割
给定长度序列(如 {3, 5, 2}),将列表依次按 3、5、2 个元素分成子列表。可用 Internal`PartitionRagged 或 TakeDrop 等实现。核心思路:每次 Take[list, n] 与 Drop[list, n],循环直到长度序列用完。