如何将数组添加到数组(索引位置到索引位置?)以在 Groovy 脚本中制作多维数组

how to add an array to an array, (index location to index location?) to make a multidimensional array in Groovy script

我在两个单独的列表中有两组数据(我正在使用 soapui 打开 groovy 脚本)- 已经过 XmlSlurper().parseText() 不确定这是否重要

a = [c1,c2,c3] 
b = [0 100, 0 50 100, 0 500 1000]

并且我想将它们组合起来(位置 0 到位置 0,然后位置 1 到位置 1 等)像这样

c = [[c1,0 100],[c2,0 50 100],[c3,0 500 100]]

我目前的代码

def splitList(list, splitAt) 
{
    list.inject([]) { curr, val ->
    if(curr.size() == 0 || val == splitAt) 
    {
        curr << []
    }
        curr[-1] << val
        curr
    }
}

def c = [a, splitList(b, 0)].transpose()*.flatten()

当我 log.info c 我得到 [[c1,0 100, 0 50 100, 0 500 100]]

因此,鉴于您的两个列表:

def a = ['c1','c2','c3']
def b = [0, 100, 0, 50, 100, 0, 500, 1000]

您可以定义一个函数,在每次看到给定值时拆分列表:

def splitList(list, splitAt) {
    list.inject([]) { curr, val ->
        if(curr.size() == 0 || val == splitAt) {
            curr << []
        }
        curr[-1] << val
        curr
    }
}

所以调用splitList(b, 0)returns[[0, 100], [0, 50, 100], [0, 500, 1000]]

然后使用这个(以及transposeflatten)得到:

def c = [a, splitList(b, 0)].transpose()*.flatten()

这样:

assert c == [['c1', 0, 100], ['c2', 0, 50, 100], ['c3', 0, 500, 1000]]

你可以这样做...

count = 0
c = a.collect {
    [it, b[count++]]
}

该代码跳过任何错误处理,只是假设 ab 具有相同数量的元素。