scala 提取元组列表中的第二个元组元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16389738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 05:15:45  来源:igfitidea点击:

Extract second tuple element in list of tuples

scalamaptuples

提问by More Than Five

I have a Map where each value is a list of Tuples such as:

我有一个 Map,其中每个值都是一个元组列表,例如:

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

改变每个值的最scala-thonic方法仍然是一个列表,但只是每个元组的第二个元素

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?

有小费吗?

采纳答案by cmbaxter

Try this:

试试这个:

    myMap.mapValues(_.map(_._2))

The value passed to mapValuesis a List[(Char,Integer)], so you have to further map that to the second element of the tuple.

传递给的值mapValues是 a List[(Char,Integer)],因此您必须进一步将其映射到元组的第二个元素。

回答by Chengye Zhao

Would that work for you?

这对你有用吗?

val a = List(('a',1), ('b', 4), ('c', 3))
a.map(_._2)

回答by trenobus

Note that mapValues() returns a view on myMap. If myMap is mutable and is modified, the corresponding changes will appear in the map returned by mapValues. If you really don't want your original map after the transformation, you may want to use map() instead of mapValues():

请注意 mapValues() 返回 myMap 上的视图。如果 myMap 是可变的并且被修改了,相应的变化就会出现在 mapValues 返回的地图中。如果您真的不想要转换后的原始地图,您可能需要使用 map() 而不是 mapValues():

myMap.map(pair => (pair._1, pair._2.map(_._2)))

回答by henko

Another way is using unzipwhich turns a list of tuples into a tuple of lists. It is especially useful if you actually want both values from the tuples.

另一种方法是使用unzipwhich 将元组列表转换为列表元组。如果您确实想要元组中的两个值,它就特别有用。

val list = List(('a',1), ('b', 4), ('c', 3))

val (letters, numbers) = list.unzip
// letters: List[Char] = List(a, b, c)
// numbers: List[Int] = List(1, 4, 3)