我在分析Scala中的TSV文件时遇到了一些问题。下面是对代码执行操作的代码。
var lines = file.map(_.split('\n'))
var nodes = lines.foreach( _.split('\t').map(_(1),_(2)).groupBy(_(1)).reduceByKey(_ + _))输入
1 a 24
2 a 3
3 b 6期望操作
a 27
b 6我在执行拆分(‘\t’)时遇到了一个错误,理由是它不是ArrayString的成员,这是非常奇怪的,因为foreach中的_应该指每次只取一个元素。感谢你的帮助
发布于 2014-11-04 22:51:01
首先,外汇的分配是单位,所以这不是你想要的。使用不变的数量。也不清楚什么是格式文件,所以您必须在那里得到一个字符串。
val file = "1\ta\t24\n2\ta\t3\n3\tb\t6"
val lines = file.split("\n")
val nodes = lines.map(_.split("\t")).map(a => (a(1),a(2))).groupBy(_._1).map(a => (a._1,a._2.map(b => b._2.toInt).sum))
//Map(b -> 6, a -> 27)这是个大烂摊子,所以我试着把它分解一下:
val lines = file.split("\n") //split string into array of lines
val nodes = lines.map(_.split("\t")) //split each line into array of strings
.map(a => (a(1),a(2))) //get just the second two items from the array as a tuple
.groupBy(_._1) //group by the first item in the tuple
.map(a => (a._1,a._2.map(b => b._2.toInt).sum)) //take each tuple and map the second value (an array of strings) into an array of ints and get the sum如果您不喜欢最终输出的映射,可以使用toList轻松地更改它,或者将映射映射到您想要的任何东西。
https://stackoverflow.com/questions/26745781
复制相似问题