将列表拆分为 N 大小的较小列表 [英] Split a List into smaller lists of N size

查看:28
本文介绍了将列表拆分为 N 大小的较小列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个列表拆分为一系列较小的列表.

I am attempting to split a list into a series of smaller lists.

我的问题:我拆分列表的功能没有将它们拆分为正确大小的列表.它应该将它们拆分为大小为 30 的列表,而是将它们拆分为大小为 114 的列表?

My Problem: My function to split lists doesn't split them into lists of the correct size. It should split them into lists of size 30 but instead it splits them into lists of size 114?

如何让我的函数将一个列表拆分成 X 个大小30 或更少的列表?

How can I make my function split a list into X number of Lists of size 30 or less?

public static List<List<float[]>> splitList(List <float[]> locations, int nSize=30) 
{       
    List<List<float[]>> list = new List<List<float[]>>();

    for (int i=(int)(Math.Ceiling((decimal)(locations.Count/nSize))); i>=0; i--) {
        List <float[]> subLocat = new List <float[]>(locations); 

        if (subLocat.Count >= ((i*nSize)+nSize))
            subLocat.RemoveRange(i*nSize, nSize);
        else subLocat.RemoveRange(i*nSize, subLocat.Count-(i*nSize));

        Debug.Log ("Index: "+i.ToString()+", Size: "+subLocat.Count.ToString());
        list.Add (subLocat);
    }

    return list;
}

如果我在大小为 144 的列表上使用该函数,则输出为:

If I use the function on a list of size 144 then the output is:

索引:4,大小:120
索引:3,尺寸:114
索引:2,尺寸:114
索引:1,尺寸:114
索引:0,大小:114

Index: 4, Size: 120
Index: 3, Size: 114
Index: 2, Size: 114
Index: 1, Size: 114
Index: 0, Size: 114

推荐答案

public static List<List<float[]>> SplitList(List<float[]> locations, int nSize=30)  
{        
    var list = new List<List<float[]>>(); 

    for (int i = 0; i < locations.Count; i += nSize) 
    { 
        list.Add(locations.GetRange(i, Math.Min(nSize, locations.Count - i))); 
    } 

    return list; 
} 

通用版本:

public static IEnumerable<List<T>> SplitList<T>(List<T> locations, int nSize=30)  
{        
    for (int i = 0; i < locations.Count; i += nSize) 
    { 
        yield return locations.GetRange(i, Math.Min(nSize, locations.Count - i)); 
    }  
} 

这篇关于将列表拆分为 N 大小的较小列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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