如何在Groovy中将列表拆分为相同大小的列表? [英] How to split a list into equal sized lists in Groovy?

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

问题描述



  def array = [1,2,3,4,5,6] 

是否有内置的允许我这样做(或类似的):

  array.split(2)

并获得:

  [[1,2],[3,4],[5,6]] 

解决方案我同意Chris的观点,即groovy没有任何内容可以处理这个问题(至少对于2个以上的分区),但是我将你的问题解释为提出与他不同的问题。这里有一个实现我认为你所要求的:

  def分区(数组,大小){
def partitions = []
int partitionCount = array.size()/ size

partitionCount.times {partitionNumber - >
def start = partitionNumber * size
def end = start + size - 1
分区<<数组[开始..结束]
}

if(array.size()%size)分区<< array [partitionCount * size ..- 1]
返回分区
}


def origList = [1,2,3,4,5,6]
assert [[1],[2],[3],[4],[5],[6]]分区(origList,1)
assert [[1,2] 3,4],[5,6]] == partition(origList,2)
assert [[1,2,3],[4,5,6]] == partition(origList,3)
assert [[1,2,3,4],[5,6]]分区(origList,4)
assert [[1,2,3,4,5],[6] ] ==分区(origList,5)
assert [[1,2,3,4,5,6]] ==分区(origList,6)
pre>

If I have this:

def array = [1,2,3,4,5,6]

Is there some built-in which allows me to do this ( or something similar ):

array.split(2)

and get:

[[1,2],[3,4],[5,6]]

?

解决方案

I agree with Chris that there isn't anything built into groovy to handle this (at least for more than 2 partitions), but I interpreted your question to be asking something different than he did. Here's an implementation that does what I think you're asking for:

def partition(array, size) {
    def partitions = []
    int partitionCount = array.size() / size

    partitionCount.times { partitionNumber ->
        def start = partitionNumber * size 
        def end = start + size - 1
        partitions << array[start..end]    
    }

    if (array.size() % size) partitions << array[partitionCount * size..-1]
    return partitions    
}


def origList = [1, 2, 3, 4, 5, 6]
assert [[1], [2], [3], [4], [5], [6]] == partition(origList, 1)
assert [[1, 2], [3, 4], [5, 6]] == partition(origList, 2)
assert [[1, 2, 3], [4, 5, 6]] == partition(origList, 3)
assert [[1, 2, 3, 4], [5, 6]] == partition(origList, 4)
assert [[1, 2, 3, 4, 5], [6]] == partition(origList, 5)
assert [[1, 2, 3, 4, 5, 6]] == partition(origList, 6)

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

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