Zip multiple sequences

后端 未结 7 1716
眼角桃花
眼角桃花 2020-12-06 09:20

I am trying to zip multiple sequences to form a long tuple:

val ints = List(1,2,3)
val chars = List(\'a\', \'b\', \'c\')
val strings = List(\"Al         


        
相关标签:
7条回答
  • 2020-12-06 09:47

    I would create a class which represents the data sets:

    case class DataSet(int: Int, char: Char, string: String, bool: Boolean)
    

    This brings nicer names for accessing the values instead of _N we have in tuples. If the lists can have different sizes the shortest should be chosen:

    val min = List(ints, chars, strings, bools).map(_.size).min
    

    Now it is possible to extract the data:

    val dataSets = (0 until min) map { i => DataSet(ints(i), chars(i), strings(i), bools(i)) }
    

    When the original lists can contain a lot of values it is better to make them to a IndexedSeq so that the access time is O(1).

    0 讨论(0)
提交回复
热议问题