Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract second tuple element in list of tuples

Tags:

tuples

map

scala

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?

like image 561
More Than Five Avatar asked May 05 '13 22:05

More Than Five


People also ask

How do you get the second value in a list Python?

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.

How do you access an element in a tuple in a list?

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.

How do you extract elements from a tuple in Python?

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.

How do you find the nth element of a tuple in Python?

The way to get the nth item in a tuple is to use std::get: std::get<n>(my_tuple) .


2 Answers

Would that work for you?

val a = List(('a',1), ('b', 4), ('c', 3))
a.map(_._2)
like image 180
Chengye Zhao Avatar answered Oct 24 '22 08:10

Chengye Zhao


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.

like image 22
cmbaxter Avatar answered Oct 24 '22 09:10

cmbaxter