Is there a scala list operation that makes tuples from lists?

前端 未结 3 1687
我寻月下人不归
我寻月下人不归 2020-12-19 09:07

I\'m trying to process triplets in a list. Imperatively, I could do this:

for(i = 1; i < list.length-1; i++)
{
   process( list[i-1], list[i], list[i+1]          


        
相关标签:
3条回答
  • 2020-12-19 09:43
    val data = List(1,2,3,4,5,6,7,8,9,10)
    val tuples = data.sliding(3).toList
    // tuples would be List(List(1,2,3), List(2,3,4), List(3,4,5), List(4,5,6) ... )
    
    0 讨论(0)
  • 2020-12-19 09:43

    I know you got the answer you wanted, but the technically correct answer is no. There's no general method that takes a list and returns tuples of variable arity because there's no way to represent that type signature in Scala at the present.

    0 讨论(0)
  • 2020-12-19 09:45

    Pablo's solution isn't entirely correct, you still need to transform the list of lists into a list of tuples:

    val data = List(1,2,3,4,5,6,7,8,9,10)
    val tuples = data.sliding(3).toList.collect{ case List(x,y,z) => (x,y,z) }
    //--> tuples: List[(Int, Int, Int)] = List((1,2,3), (2,3,4), (3,4,5), ...
    
    0 讨论(0)
提交回复
热议问题