列表中具有奇数和偶数索引的Zip元素 [英] Zip elements with odd and even indices in a list

查看:66
本文介绍了列表中具有奇数和偶数索引的Zip元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想压缩列表中的偶数和奇数元素以形成成对的列表,像这样:

I want to zip even and odd elements in a list to make a list of pairs, like that:

["A", "B", "C", "D", "E", "F"] -> [("A", "B"), ("C", "D"), ("E", "F")]

以实用的方式优雅地做到这一点的最简洁的表达是什么?

What is the most concise expression to do this in elegant in functional way?

推荐答案

在2.8中,您可能会使用以下方法:

In 2.8, you'd probably use methods:

scala> val a = "ABCDEF".toList.map(_.toString) 
a: List[java.lang.String] = List(A, B, C, D, E, F)

scala> a.grouped(2).partialMap{ case List(a,b) => (a,b) }.toList
res0: List[(java.lang.String, java.lang.String)] = List((A,B), (C,D), (E,F))

(这是2.8.0 Beta1;最新的主干使用 collect 代替 partialMap .)

(This is 2.8.0 Beta1; the latest trunk has collect in place of partialMap.)

在2.7中(而不是在2.8中表现不佳),您可以像Legoscia一样创建递归方法:

In 2.7--and not a bad runner-up in 2.8--you could create a recursive method as legoscia did:

def zipPairs[A](la : List[A]): List[(A,A)] = la match {
  case a :: b :: rest => (a,b) :: zipPairs(rest)
  case _ => Nil
}

scala> zipPairs(a)
res1: List[(java.lang.String, java.lang.String)] = List((A,B), (C,D), (E,F))

这是另一个适用于2.7的简要方法:

here's another briefer approach that works on 2.7 also:

scala> (a zip a.drop(1)).zipWithIndex.filter(_._2 % 2 == 0).map(_._1)
res2: List[(java.lang.String, java.lang.String)] = List((A,B), (C,D), (E,F))

(请注意,使用 drop(1)代替 tail ,这样它可以与空列表一起使用.)

(Note the use of drop(1) instead of tail so it works with empty lists.)

这篇关于列表中具有奇数和偶数索引的Zip元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆