Scala - Two Lists to Tuple List

社会主义新天地 提交于 2019-12-28 16:33:50

问题


Last year I had quite a bit of experience with standard ML, but I haven't done any real functional programming in about 10 months. Now that I'm on the Scala bandwagon, I'm having trouble finding an operation which I used extensively in standard ML when writing a compiler (although to be fair, this method may not have been a library method).

Basically, I have two lists:

List("a","b","c")
List(1,2,3)

And I want an operation that will give me a list of tuples like this:

List(("a",1), ("b",2), ("c",3))

Is there a standard Scala function I can use to get this result? (I think we called it a zip function in standard ML, but that seems to refer to something different when I was searching for Scala zip functions.)


回答1:


You're right you can use zip:

val a = List("a","b","c")
// a: List[String] = List(a, b, c)

val b = List(1,2,3)
// b: List[Int] = List(1, 2, 3)

a zip b  // beautified a.zip(b) 
//res0: List[(String, Int)] = List((a,1), (b,2), (c,3))


来源:https://stackoverflow.com/questions/16423398/scala-two-lists-to-tuple-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!