I have a Map where each value is a list of Tuples such as:
List(('a',1), ('b', 4), ('c', 3)....)
what is the most scala-thonic way to change each value is still a LIst but is only the second element of each Tuple
List(1,4,3)
I have tried
myMap.mapValues(x => x._2)
And I get
error: value _2 is not a member of List[(Char, Integer)]
any tips?
Practical Data Science using Python Any element in list can be accessed using zero based index. If index is a negative number, count of index starts from end. As we want second to last element in list, use -2 as index.
In the majority of programming languages when you need to access a nested data type (such as arrays, lists, or tuples), you append the brackets to get to the innermost item. The first bracket gives you the location of the tuple in your list. The second bracket gives you the location of the item in the tuple.
Method #2 : Using filter() + lambda + all() In this, we employ filter() to extract out tuples, according to function provided by lambda, and all() as utility to test for all elements in range tuple.
The way to get the nth item in a tuple is to use std::get: std::get<n>(my_tuple) .
Would that work for you?
val a = List(('a',1), ('b', 4), ('c', 3))
a.map(_._2)
Try this:
myMap.mapValues(_.map(_._2))
The value passed to mapValues
is a List[(Char,Integer)]
, so you have to further map that to the second element of the tuple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With