You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按行限制将列表行拆分为最大规模且最均等的分组?

解决方案:按行限制均等拆分列表

需求说明

需将列表中的行按照行限制(例如RowLimit=4)拆分为尽可能大且各分组行数最均等的部分,示例如下:

  • 示例1:10行列表,期望结果:4, 3, 3
  • 示例2:9行列表,期望结果:3, 3, 3
  • 示例3:8行列表,期望结果:4, 4
  • 示例4:7行列表,期望结果:4, 3

现有代码问题

当前实现的简单按行限制拆分方法会生成不均等的分组(如10行拆分为4,4,2),无法满足需求。现有代码如下:

public List<List<string>> TextWithRowLimit(List<string> TextRows, int RowLimit)
{
    List<List<string>> list = new List<List<string>>();
    int RowLimitCounter = 1;
    List<string> TextRowPackages = new List<string>();
    for (int row = 0; row < TextRows.Count; ++row)
    {
        TextRowPackages.Add($"{TextRows[row]} ");
        if (RowLimitCounter == RowLimit)
        {
            list.Add(TextRowPackages);
            RowLimitCounter = 0;
            TextRowPackages = new List<string>();
        }
        RowLimitCounter++;
    }
    if(TextRowPackages.Count>0)
        list.Add(TextRowPackages);
    return list;
}

改进实现方案

要实现均等拆分,需先计算分组数量和每个分组的大小:

  1. 计算总行数 totalRows = TextRows.Count
  2. 确定最小分组数:groupCount = (int)Math.Ceiling((double)totalRows / RowLimit)
  3. 计算每个分组的基础大小:baseSize = totalRows / groupCount
  4. 计算有多少个分组需要多一行:extraGroups = totalRows % groupCount
  5. 前extraGroups个分组大小为baseSize +1,剩余分组为baseSize(确保不超过RowLimit)

以下是改进后的C#代码:

public List<List<string>> SplitIntoEqualGroups(List<string> textRows, int rowLimit)
{
    var result = new List<List<string>>();
    int totalRows = textRows.Count;
    if (totalRows == 0) return result;

    // 计算分组数:确保每个分组不超过rowLimit,且尽可能均等
    int groupCount = (int)Math.Ceiling((double)totalRows / rowLimit);
    // 防御性调整:避免基础大小超过行限制
    while ((totalRows + groupCount - 1) / groupCount > rowLimit)
    {
        groupCount++;
    }

    int baseSize = totalRows / groupCount;
    int extraGroups = totalRows % groupCount;

    int currentIndex = 0;
    for (int i = 0; i < groupCount; i++)
    {
        int currentGroupSize = (i < extraGroups) ? baseSize + 1 : baseSize;
        // 确保分组大小不超过行限制
        currentGroupSize = Math.Min(currentGroupSize, rowLimit);
        var group = textRows.GetRange(currentIndex, currentGroupSize);
        // 保留原代码的末尾空格格式
        var formattedGroup = group.Select(row => $"{row} ").ToList();
        result.Add(formattedGroup);
        currentIndex += currentGroupSize;
    }

    return result;
}

代码说明

  • 分组数计算:通过总行数除以行限制向上取整得到初始分组数,确保每个分组不超过行限制。
  • 大小分配:前N个分组多一行,剩余分组为基础大小,保证分组尽可能均等。
  • 防御性处理:添加逻辑确保分组大小不超过行限制,避免极端情况出错。
  • 格式保持:保留了原代码中每个字符串末尾添加空格的逻辑。

验证示例

  • 10行,RowLimit=4:分组数=3,baseSize=3,extraGroups=1 → 4,3,3
  • 9行,RowLimit=4:分组数=3,baseSize=3,extraGroups=0 →3,3,3
  • 8行,RowLimit=4:分组数=2,baseSize=4,extraGroups=0 →4,4
  • 7行,RowLimit=4:分组数=2,baseSize=3,extraGroups=1 →4,3

内容的提问来源于stack exchange,提问作者silas-paul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 11:10:33