Groovy压缩列表或按级别展平

时间:2014-07-11 07:52:38

标签: list groovy flatten

我正在尝试压缩两个列表。我找到了一个使用transpose的解决方案(来自此链接:Is there any analog for Scala 'zip' function in Groovy?),但结果并不完全符合我的预期。我希望压缩列表!我的意思是拉链。

假设:

a = [ [1,2,3] , [4,5,6], [7,8,9] ]
b = [ ['a','b','c'] , ['d','e','f'], ['g','h','j']]

预期结果:

zipped = [ [1,2,3], 
           ['a','b','c'], 
           [4,5,6], 
           ['d','e','f'], (...) ]

但转置让我:

[a,b].transpose() = [ [[1,2,3],['a','b','c']]
                      [[4,5,6],['d','e','f']]
                      [[7,8,9],['g','h','j']] ]

我试图以某种方式压扁最后一个列表,但没有按级别扁平化。每个列表都在变平,我只想离开“行”列表,

3 个答案:

答案 0 :(得分:3)

[a, b].transpose().collectMany { it }

答案 1 :(得分:1)

flatten()应该是在这里工作的好人选,但它是递归的,最终会使树的最后一层变平。我想使用inject建议变体:

def zip(a,b) {
    [a,b].transpose().inject([]) { result, list -> result + list }
}

def a = [ [1,2,3] , [4,5,6], [7,8,9] ]
def b = [ ['a','b','c'] , ['d','e','f'], ['g','h','j']]

assert zip(a,b) == [
    [1, 2, 3], 
    ['a', 'b', 'c'], 
    [4, 5, 6], 
    ['d', 'e', 'f'], 
    [7, 8, 9], 
    ['g', 'h', 'j']
]

答案 2 :(得分:0)

我想到了两个想法:

def a = [ [1,2,3] , [4,5,6], [7,8,9] ]
def b = [ ['a','b','c'] , ['d','e','f'], ['g','h','j']]

def l = []
[a,b].transpose().collect { it.collect { l << it} }
assert l ==  [[1, 2, 3], ['a', 'b', 'c'], [4, 5, 6], ['d', 'e', 'f'], [7, 8, 9], ['g', 'h', 'j']]


def k = [a,b].transpose().inject([]) {acc, val -> 
    val.collect {acc << it }
    acc
}
assert k ==  [[1, 2, 3], ['a', 'b', 'c'], [4, 5, 6], ['d', 'e', 'f'], [7, 8, 9], ['g', 'h', 'j']]