开发者

Java code translation of Python array-splitting code

Can someone please give the Java equivalent of the below python (which slices a given array into given parts) which was originally written by ChristopheD here:

def split_list(alist, wanted_parts=1):
   length = len(alist)
   return [ alist[i*length // wanted_parts: (i+1)*length // wanted_parts] 
            for i in range(wanted_parts) ]

I don't know any python but can really use the above code in my Java ap开发者_JAVA技巧p. Thanks


Maybe something like this:

List<List<T>> splitList(List<T> alist, int wantedParts) {
    ArrayList<List<T>> result = new ArrayList<List<T>>();
    int length = alist.length;

    for (int i = 0; i < wantedParts; i++) {
        result.append(alist.subList(i*length/wantedParts,
                                    (i+1)*length/wantedParts));
    }

    return result;
}

If your alist will be structurally modified later in any way, you will have to make a copy of the sublist created by the subList method within the code, otherwise the results will be unpredictable.


Don't reinvent the wheel, the google collections api has a function called partition which does precisely that

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜