我正在尝试结合" n"在Scala中列出,但我是这个sintaxis的初学者。我有这个:
例如,如果我有" n"列表我想要组合所有第一个元素,所有秒元素等:
var a = List("book1","book2","book3","book4")
var b = List(103, 102, 101, 100)
我想举例如:
book1 103
book2 102
book3 101
book4 100
我做了这个方法来阅读" n"列表,但我只能显示每个列表但不能合并。
def listar(x: List[column]): List[Any] = {
if (x.isEmpty) List()
else print(x.head.values)
if (x.isEmpty) {
List()
} else {
listar(x.tail)
}
}
// Here I'm sending one list with more list, It's means list(list(),list(),list()...)
listar(book.columns)
我该怎么办?非常感谢你的帮助。
这样的想法:
var a = List("book1", "book2", "book3", "book4")
var b = List(103, 102, 101, 100)
var c = List ("otro1","otro2","otro3","otro4")
var d = List (1,2,3,4)
var e = List(a,b,c,d)
book1 103 otro1 1
book2 102 otro2 2
我如何组合所有firstElments,SecondsElement等....
答案 0 :(得分:2)
使用transpose
:
val a = List("book1", "book2", "book3", "book4")
val b = List(103, 102, 101, 100)
val c = List("otro1", "otro2", "otro3", "otro4")
val d = List(1, 2, 3, 4)
val e = List(a, b, c, d)
val combined = e.transpose
// List(List(book1, 103, otro1, 1), List(book2, 102, otro2, 2), List(book3, 101, otro3, 3), List(book4, 100, otro4, 4))
combined.foreach(println)
/* prints:
List(book1, 103, otro1, 1)
List(book2, 102, otro2, 2)
List(book3, 101, otro3, 3)
List(book4, 100, otro4, 4) */
combined
是List[List[Any]]
。
答案 1 :(得分:0)
你会得到List((ElementFromFirstList, ElementFromSecondList))
例如,
scala> a.zipWithIndex.map { case (key: String, index: Int) => (key -> b(index)) }
res1: List[(String, Int)] = List((book1,103), (book2,102), (book3,101), (book4,100))
如果你想简单地想要Map
firstelem,那么secondelem
scala> a.zipWithIndex.map { case (key, index) => (key -> b(index)) }.toMap
res10: scala.collection.immutable.Map[String,Int] = Map(book1 -> 103, book2 -> 102, book3 -> 101, book4 -> 100)
我假设list1.size == list2.size