如何使用地图将具有全名的列表转换为(name,surname)的元组
我在将 List(Name Surname, Name Surname, ....) 列表转换为 List((name, surname), (name,surname)) 时遇到问题。我试过使用map,case但它说它找不到值“+”
val lines = io.Source.fromResource("nazwiska.txt").getLines.toList
println(lines)
val linesMapped = lines.map{case x+" "+y => (x,y) }
回答
你快到了,但尝试使用内插字符串模式
lines.map { case s"$firstname $surname" => (firstname, surname) }
还考虑切换到collect过滤掉格式错误的名称,否则上面的映射会爆炸
lines.collect { case s"$firstname $surname" => (firstname, surname) }
- Note that it will fail for people who have multiple first and last names, at least common in Latin America like mine :p so you may want to use a **Regex** instead - But, probably for a simple academic exercise it would be an overkill.