简体   繁体   English

是否有scala列表操作从列表中生成元组?

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

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] )
}

Is there a List function in Scala (or how would one write it) that can do something like this: 在Scala中是否有一个List函数(或者如何编写它)可以执行以下操作:

val data = [1,2,3,4,5,6,7,8,9,10]
val tuples = data.some_magic_func
tuples would be[(1,2,3), (2,3,4), (3,4,5), (4,5,6) ... ]

Thanks! 谢谢!

Pablo's solution isn't entirely correct, you still need to transform the list of lists into a list of tuples: Pablo的解决方案并不完全正确,您仍需要将列表列表转换为元组列表:

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), ...

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. 没有通用方法可以获取列表并返回变量arity的元组,因为目前无法在Scala中表示该类型签名。

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) ... )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM