考慮這個解決方案,雖然它有點脆弱(例如,當鍵不對齊時)。此外,這將「第一個」列表修改爲副作用,這有點味道。
// 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
是清單中的'A'和'B'元素還是標記?如果元素,他們是字符串? –
A和B是列表中可以用作鍵的一致元素,但最終我只需要每個元素的第一個實例。 –
是的,他們是字符串。 –