Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala list of list count different elements per sublist index

Tags:

list

scala

I have a list of lists with the following data

val list = List(List("a","b","c"),List("d","e","f"),List("a","a","a"))

I want to disicover how many different data do I have in each position of the sublists

1 -> List("a","d","a")

2 -> List("b","e","a")

3 -> List("c","f","a")

Is there a way to do that? It doesn't need to be indexed, but I need the amount of different values per sublist index, the result could also be

2 // different values a and d

3 // different values b, e and a

3 // different values c, f and a

like image 333
dirceusemighini Avatar asked Jan 25 '26 04:01

dirceusemighini


1 Answers

As I noted in a comment on Jhonny Everson's (almost right but now deleted) answer, you can use transpose to get a list of the columns, and then distinct to remove duplicates:

scala> list.transpose.map(_.distinct.size)
res0: List[Int] = List(2, 3, 3)

This will throw an exception if all the lists don't have the same size, but that's probably what you want.

like image 97
Travis Brown Avatar answered Jan 26 '26 20:01

Travis Brown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!