简体   繁体   English

使用折叠或贴图转换集合

[英]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 : 这段代码将csv中的第一个String删除后,将String的List集合转换为Doubles:

  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 ? 可以使用fold或map重写它,以便不对CSV列表中的元素长度进行硬编码吗? Currently this is just correct where each String contains 3 CSV elements. 当前,这是正确的,其中每个字符串包含3个CSV元素。 But I'm unsure how to re-write it using N elements such as ("A1,2,10,4,5") 但是我不确定如何使用N个元素(例如("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 ). 至于没有嵌套的.map是否可行,这是令人怀疑的:您的.csv代表一个矩阵,通常使用嵌套的for循环(或.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 .split(',')在逗号分隔符处分割
  2. .drop(1) removes the first element .drop(1)删除第一个元素
  3. .map(_.toDouble) converts the strings to floating point numbers .map(_.toDouble)将字符串转换为浮点数

Update: This is equivalent to your proposed solution. 更新:这等效于您建议的解决方案。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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