1

我有两个长长的列表:

first = [[A, 2, 4, 6], [B, 1, 3, 5]...]
second = [[A, 8, 10, 12], [B, 7, 9, 11]...]

想合并成(订单保留)

first = [[A, 2, 4, 6, 8, 10, 12], [B, 1, 3, 5, 7, 9, 11]...]

(我将在函数调用的“第二”类结果的每个{}中执行此操作,因此我需要继续合并到“第一”中)我想我正在寻找某种加法,加上展平,但是我不太明白。任何帮助,将不胜感激。

谢谢!

4

3 回答 3

4

如果:

  • 列表总是匹配的,因此如果有一个“A”记录,first则有一个 in second,如果有一个“B”记录first,则有一个 in second,依此类推
  • 列表以相同的顺序排列

然后你可以逃脱:

[ first, second ].transpose()*.flatten()*.unique()
于 2013-07-25T08:09:23.937 回答
3

这是一种方法:

def merge(a, b) {
  tmp = b.collectEntries { [it.first(), it.tail()] }
  return a.collect { it + tmp[it.first()] }
}

它创建一个Map由第二个列表中每个条目的第一个子条目作为键的临时对象,然后在遍历第一个列表时查找要附加的适当内容。

例如:

A = "A"
B = "B"
​first = [[A, 2, 4, 6], [B, 1, 3, 5]]
second = [[A, 8, 10, 12], [B, 7, 9, 11]]

println merge(first, second)

它可能对缺少的元素等更加健壮。

于 2013-07-25T01:08:21.287 回答
0

考虑这个解决方案,虽然它有点脆弱(例如,当键不对齐时)。此外,这会将“第一个”列表修改为副作用,这有点异味。

// modifies 'first' as a side-effect
def merge = { def first, def subSecond ->
    def subFirst = first.find { it[0] == subSecond[0] }
    if (subFirst) {
        subFirst.addAll( subSecond[1..subSecond.size()-1] )
    }
}

// tests 

def first = null
def results = null

first = [["A",2,4,6],["B",1,3,5]]
results = []
results.each { def subSecond -> merge(first,subSecond) }
assert [["A",2,4,6],["B",1,3,5]] == first

first = [["A",2,4,6],["B",1,3,5]]
results = [ ["A",8,10,12] ]
results.each { def subSecond -> merge(first,subSecond) }
assert [["A",2,4,6,8,10,12],["B",1,3,5]] == first

first = [["A",2,4,6],["B",1,3,5]]
results = [ ["A",8,10,12],["B",7,9,11]  ]
results.each { def subSecond -> merge(first,subSecond) }
assert [["A",2,4,6,8,10,12],["B",1,3,5,7,9,11]] == first
于 2013-07-25T01:08:12.547 回答