scala 过滤元组列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16450100/
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
Filtering a list of tuples
提问by More Than Five
I have a list of tuples and I want to filter out the all elements where the second value in the tuple is not equal to 7.
我有一个元组列表,我想过滤掉元组中第二个值不等于 7 的所有元素。
I do:
我做:
valuesAsList.filter(x=>x._2 != 7)
Can I use wildcard notation to make this even shorter?
我可以使用通配符来使它更短吗?
Thanks.
谢谢。
回答by om-nom-nom
You can
你可以
valuesAsList.filter(_._2 != 7)
But I doubt it should be preferred over your example or this (think readability):
但我怀疑它应该比你的例子或这个(想想可读性)更受欢迎:
valuesAsList.filter {case (_, v) => v != 7}
回答by Richard Sitze
Fairly straight forward, with no real advantage IMHO:
相当直接,恕我直言没有真正的优势:
valuesAsList.filter(_._2 != 7)
回答by Azeezullah shariff
For array of tuples, we can use for with yield which will returns an array
对于元组数组,我们可以使用 for with yield 返回一个数组
scala> val str = Array((2,Hello), (3,MyNameIs), (8,Lolo))
scala> val str = Array((2,Hello), (3,MyNameIs), (8,Lolo))
res34: Array[(Int, String)] = Array((2,Hello), (3,MyNameIs), (8,Lolo))
res34: Array[(Int, String)] = Array((2,Hello), (3,MyNameIs), (8,Lolo))
scala> for(i <- str if(i._2.size > 4)) yield (i._1,i._2.toLowerCase)
Scala> for(i <- str if(i._2.size > 4)) yield (i._1,i._2.toLowerCase)
res35: Array[(Int, String)] = Array((2,hello), (3,mynameis))
res35: Array[(Int, String)] = Array((2,hello), (3,mynameis))

