如何使用scala基于列为每条线创建贴图?

如何使用scala基于列为每条线创建贴图?,scala,Scala,我需要基于使用scala的列为每一行创建映射,例如 sunny,hot,high,FALSE,no overcast,hot,high,FALSE,yes rainy,mild,high,FALSE,yes 我希望输出为 RDD[List( Map( '0 -> 'sunny, '1 -> 'hot, '2 -> 'high, '3 -> 'false, '4 -> 'no ), Map( '0 ->

我需要基于使用scala的列为每一行创建映射,例如

sunny,hot,high,FALSE,no
overcast,hot,high,FALSE,yes
rainy,mild,high,FALSE,yes
我希望输出为

RDD[List(
  Map(
    '0 -> 'sunny,
    '1 -> 'hot,
    '2 -> 'high,
    '3 -> 'false,
    '4 -> 'no
  ),
  Map(
    '0 -> 'overcast,
    '1 -> 'hot,
    '2 -> 'high,
    '3 -> 'false,
    '4 -> 'yes
  ),
  Map(
    '0 -> 'rainy,
    '1 -> 'mild,
    '2 -> 'high,
    '3 -> 'false,
    '4 -> 'yes
  )
)]

这里,我们考虑每个列,列号是键,列值是键值对中的值。< /P>普通Scala



  • 在分隔符上拆分文本
  • 将序列“映射”到(值、索引)的元组

    “Seq('a','b')。zipWithIndex'产生'Seq[(Char,Int)]=列表((a,0),(b,1))”


我们可以将功能改进为:

s.split("\n").map { line =>
  line.split(",").zipWithIndex.map(_.swap).toMap
}.toList
  • 因为'zipWithIndex'的结果是元组,它们具有函数,所以我们不需要自己交换元素

为了火花
sc.textFile().map{line=>
line.split(“,”).zipWithIndex.map(u.swap).toMap
}

谢谢@Paul

,如果您将
s.split(“\n”)
替换为
sc.textFile()
,并删除
.toList
谢谢@Paul-我添加了您的改进(我想我需要学习Spark)我不太了解Spark,但为了回答关于它的另一个问题,我学到了一点。有相当多的基本问题正在讨论中asked@Paul,这是RDD[…],我想通过读取文本文件来列出[Map[Int,String]]这个答案的第一部分是纯Scala。读取文本文件只是Source.fromPath(“myfile.txt”).getLines()。看看你是否需要更多信息。
yields:
List(Map(0 -> sunny, 1 -> hot, 2 -> high, 3 -> FALSE, 4 -> no), 
     Map(0 -> overcast, 1 -> hot, 2 -> high, 3 -> FALSE, 4 -> yes), 
     Map(0 -> rainy, 1 -> mild, 2 -> high, 3 -> FALSE, 4 -> yes))
s.split("\n").map { line =>
  line.split(",").zipWithIndex.map(_.swap).toMap
}.toList
sc.textFile(<file-with-data>).map { line =>
  line.split(",").zipWithIndex.map(_.swap).toMap
}