如何将 Scala 列表成对?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11248739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:17:30  来源:igfitidea点击:

How do you turn a Scala list into pairs?

scala

提问by Garrett Hall

I am trying to split Scala list like List(1,2,3,4)into pairs (1,2) (2,3) (3,4), what's a simple way to do this?

我正在尝试将 Scala 列表List(1,2,3,4)分成对(1,2) (2,3) (3,4),有什么简单的方法可以做到这一点?

回答by Luigi Plinge

val xs = List(1,2,3,4)
xs zip xs.tail
  // res1: List[(Int, Int)] = List((1,2), (2,3), (3,4))

As the docs say, zip

正如文档所说, zip

Returns a list formed from this list and another iterable collection by combining corresponding elements in pairs. If one of the two collections is longer than the other, its remaining elements are ignored.

通过将相应的元素成对组合,返回由此列表和另一个可迭代集合形成的列表。如果两个集合之一比另一个长,则忽略其剩余元素。

So List('a,'b,'c,'d)zipped with List('x,'y,'z)is List(('a,'x), ('b,'y), ('c,'z))with the final 'dof the first one ignored.

所以List('a,'b,'c,'d)压缩List('x,'y,'z)是第一个List(('a,'x), ('b,'y), ('c,'z))的最后'd一个被忽略。

From your example, the tailof List(1,2,3,4)is List(2,3,4)so you can see how these zip together in pairs.

从您的示例中,tailofList(1,2,3,4)List(2,3,4)这样您就可以看到这些是如何成对地压缩在一起的。

回答by Jakob Odersky

To produce a list of pairs (i.e. tuples) try this

要产生对(即元组)的列表,试试这个

List(1,2,3,4,5).sliding(2).collect{case List(a,b) => (a,b)}.toList

回答by Brian

List(1,2,3,4).sliding(2).map(x => (x.head, x.tail.head)).toList
res0: List[(Int, Int)] = List((1,2), (2,3), (3,4))