简体   繁体   中英

Using fold or map to convert a collection

This code converts a List collection of Strings to Doubles with the first String in csv removed :

  val points = List(("A1,2,10"), ("A2,2,5"), ("A3,8,4"), ("A4,5,8"), ("A5,7,5"), ("A6,6,4"), ("A7,1,2"), ("A8,4,9"))
  points.map (m => (m.split(",")(1).toDouble , m.split(",")(2).toDouble))
  //> res0: List[(Double, Double)] = List((2.0,10.0), (2.0,5.0), (8.0,4.0), (5.0,8.0), (7.0,5.0), (6.0,4.0), (1.0,2.0), (4.0,9.0))

Can this be re-written using fold or map so that the length number of elements in the CSV list is not hardcoded ? Currently this is just correct where each String contains 3 CSV elements. But I'm unsure how to re-write it using N elements such as ("A1,2,10,4,5")

Update : Here is possible solution :

  points.map (m => (m.split(",").tail).map(m2 => m2.toDouble))

Can be achieved using single traversal instead of two ?

scala> val points = List(("A1,2,10"), ("A2,2,5,6,7,8,9"))
points: List[String] = List(A1,2,10, A2,2,5,6,7,8,9)

scala> points.map(_.split(",").tail.map(_.toDouble))
res0: List[Array[Double]] = List(Array(2.0, 10.0), Array(2.0, 5.0, 6.0, 7.0, 8.0, 9.0))

EDIT

Pretty much was you proposed. As to whether it is doable without a nested .map , it's pretty doubtful : your .csv represents a matrix, which are usually manipulated using nested for loops (or .map ).

Tuples are not the right choice here, as tuples are generally more useful if you know the number of elements in the tuple in advance.

You could use arrays though and take advantage of the fact that you can treat arrays as collections:

points.map(_.split(',').drop(1).map(_.toDouble))
  1. .split(',') splits at the comma seperator
  2. .drop(1) removes the first element
  3. .map(_.toDouble) converts the strings to floating point numbers

Update: This is equivalent to your proposed solution.

它在外部列表上有一个迭代:

points.map(_.split(",").tail.map(_.toDouble))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM