I'm trying to get element from a list:
data =List(("2001",13.1),("2009",3.1),("2004",24.0),("2011",1.11))
Any help? Task is to print separatly Strings and numbers like:
print(x._1+" "+x._2)
but this is not working.
One good practice with functional programming is to do as much as possible with side-effect-free transformations of immutable objects.
What that means (in this case) is that you can convert the list of tuples to a list of strings, then limit your side-effect (the println
) to a single step at the very end.
val data = List(("2001",13.1),("2009",3.1),("2004",24.0),("2011",1.11))
val lines = data map { case(a,b) => a + " " + b.toString }
println(lines mkString "\n")
scala> val data =List(("2001",13.1),("2009",3.1),("2004",24.0),("2011",1.11))
data: List[(java.lang.String, Double)] = List((2001,13.1), (2009,3.1), (2004,24.0), (2011,1.11))
scala> data.foreach(x => println(x._1+" "+x._2))
2001 13.1
2009 3.1
2004 24.0
2011 1.11
val list = List(("2001",13.1),("2009",3.1),("2004",24.0),("2011",1.11))
println(list map (_.productIterator mkString " ") mkString "\n")
2001 13.1
2009 3.1
2004 24.0
2011 1.11
我将使用模式匹配,从而产生一种编程模式,该模式可以更好地缩放以用于更大的元组和更复杂的元素:
data.foreach { case (b,c) => println(b + " " + c) }
for the Strings, use
List((1,"aoeu")).foreach(((_
:Tuple2[String,_
])._1) andThen print)
for the numbers, use
List(("aoeu",13.0)).foreach((( _
:Tuple2[ _
,Double])._2) andThen print)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.