Reputation: 433
a List for example:
List(List((0,1), (1,2), (0,0), (1,1)),List((0,1), (1,2), (2,2), (3,3)))
expected:
List((0,2), (2,4), (2,2), (4,4))
how to use reduce function to add every tuple2's value from each inner List
List(List((0,1), (1,2), (0,0), (1,1)),List((0,1), (1,2), (2,2), (3,3))).reduce((a,b)=>a.zip(b))
i don't know how to realize it,so ask for help. thx
Upvotes: 0
Views: 56
Reputation: 51271
You're almost there. After the lists have been zipped, map
over it so that the resulting list of type List[((Int,Int),(Int,Int))]
can be combined to the desired type List[(Int,Int)]
.
lst.reduce { (x, y) =>
x zip y map {case ((a,b),(c,d)) => (a+c,b+d)}
}
You might also consider using zipAll()
just in case there are internal lists of different lengths.
lst.reduce { (x, y) =>
x.zipAll(y,(0,0),(0,0)).map{case ((a,b),(c,d)) => (a+c,b+d)}
}
Upvotes: 4
Reputation: 41957
@jwvh's answer should suffice your problem. But if you would like yet another way to try, then you can try as following too.
val list = List(List((0,1), (1,2), (0,0), (1,1)),List((0,1), (1,2), (2,2), (3,3)))
list.reduce((a,b) => a.zip(b).map(tuple => (tuple._1._1 + tuple._2._1, tuple._1._2 + tuple._2._2)))
Upvotes: 0