如何在Groovy中将列表拆分为相同大小的列表?

Geo*_*Geo 21 groovy list built-in

如果我有这个:

def array = [1,2,3,4,5,6]
Run Code Online (Sandbox Code Playgroud)

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

array.split(2)
Run Code Online (Sandbox Code Playgroud)

得到:

[[1,2],[3,4],[5,6]]
Run Code Online (Sandbox Code Playgroud)

tim*_*tes 62

编辑从groovy 1.8.6开始,您可以在列表中使用collat​​e方法

def origList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
assert [[1, 2, 3, 4], [5, 6, 7, 8], [9]] == origList.collate(4)
Run Code Online (Sandbox Code Playgroud)

另一种使用inject和metaClasses的方法

List.metaClass.partition = { size ->
  def rslt = delegate.inject( [ [] ] ) { ret, elem ->
    ( ret.last() << elem ).size() >= size ? ret << [] : ret
  }
  if( rslt.last()?.size() == 0 ) rslt.pop()
  rslt
}

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

assert [ [1], [2], [3], [4], [5], [6] ] == origList.partition(1)
assert [ [1, 2], [3, 4], [5, 6] ]       == origList.partition(2)
assert [ [1, 2, 3], [4, 5, 6] ]         == origList.partition(3)
assert [ [1, 2, 3, 4], [5, 6] ]         == origList.partition(4)
assert [ [1, 2, 3, 4, 5], [6] ]         == origList.partition(5)
assert [ [1, 2, 3, 4, 5, 6] ]           == origList.partition(6)
assert [ ]                              == [ ].partition(2)
Run Code Online (Sandbox Code Playgroud)

编辑:修复了空列表的问题


Ted*_*eid 16

我同意克里斯认为没有任何内容可以处理这个问题(至少超过2个分区),但我解释你的问题是要求与他不同的东西.这是一个实现,我做你认为你要求的:

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)
Run Code Online (Sandbox Code Playgroud)


ben*_*fer 12

查看groovy 1.8.6.List上有一个新的collat​​e方法.

def list = [1, 2, 3, 4]
assert list.collate(4) == [[1, 2, 3, 4]] // gets you everything   
assert list.collate(2) == [[1, 2], [3, 4]] //splits evenly
assert list.collate(3) == [[1, 2, 3], [4]] // won't split evenly, remainder in last list.
Run Code Online (Sandbox Code Playgroud)

查看Groovy List文档以获取更多信息,因为还有其他几个参数可以为您提供其他选项,包括删除其余部分.


小智 7

我一直在寻找相同的问题,我发现collate()列表的方法非常有用.

array.collate(2)
Run Code Online (Sandbox Code Playgroud)

是文档的链接.