开发者

Scala filtering tuple list

开发者 https://www.devze.com 2023-01-31 21:19 出处:网络
Question : How do you filter based on other items in a list? I got a List that looks like that List((2,2),(开发者_C百科2,1),(3,1),....)

Question : How do you filter based on other items in a list?

I got a List that looks like that

List((2,2),(开发者_C百科2,1),(3,1),....)

I want to keep the tupples which got the biggest second numbers when they got the same first ones

so something like that on output

List((2,2),(3,1),...)

with (2,1) removed because the 1 was < then 2 in (2,2)

so i need to filter based on other objects in the List how do you do that.

Efficiency is not really important since the list got at maximum 171 items


Converting a list of pairs to a map will use the last occurring entry when a given "key" occurs twice.

And a Tuple is sorted on the first element, then the second element, etc.

So:

List((2,2),(2,1),(3,1)).sorted.toMap
// = List((2,1),(2,2),(3,1)).toMap
// = Map((2,2), (3,1))

Just convert back to a list with .toList afterwards, if necessary


for ((x, y) <- lst if !lst.exists(t => x == t._1 && y < t._2)) yield (x, y)

But if you want non-quadratic complexity:

lst.groupBy(_._1).map(_._2.max).toList.sorted
0

精彩评论

暂无评论...
验证码 换一张
取 消