scala使用zip合并两个集合为二元组集合
2017-08-01 09:17
218 查看
tuple只能有tuple2到tuple22
Solution
使用zip方法合并两个集合:
上面创建了一个二元祖集合,它把两个原始集合合并为一个集合。下面我们来看下如何对zip的结果进行遍历:
一旦你遇到类似于couples这样的二元祖集合,你可以把它转化为一个map,这样看起来更方便:
注意:我们使用unzip方法可以对zip后的结果反向操作:
Problem
你想要合并两个有序集合成为一个键值对集合Solution
使用zip方法合并两个集合:scala> val women = List("Wilma", "Betty") women: List[String] = List(Wilma, Betty) scala> val men = List("Fred", "Barney") men: List[String] = List(Fred, Barney) scala> val couples = women zip men couples: List[(String, String)] = List((Wilma,Fred), (Betty,Barney))
上面创建了一个二元祖集合,它把两个原始集合合并为一个集合。下面我们来看下如何对zip的结果进行遍历:
scala> for((wife,husband) <- couples){ | println(s"$wife is merried to $husband") | } Wilma is merried to Fred Betty is merried to Barney
一旦你遇到类似于couples这样的二元祖集合,你可以把它转化为一个map,这样看起来更方便:
scala> val couplesMap = couples.toMap couplesMap: scala.collection.immutable.Map[String,String] = Map(Wilma -> Fred, Betty -> Barney)
Discussion
如果一个集合包含比另一个集合更多的元素,那么当使用zip合并集合的时候,拥有更多元素的集合中多余的元素会被丢掉。如果一个集合只包含一个元素,那么结果二元祖集合就只有一个元素。scala> val products = Array("breadsticks", "pizza", "soft drink") products: Array[String] = Array(breadsticks, pizza, soft drink) scala> val prices = Array(4) prices: Array[Int] = Array(4) scala> val productsWithPrice = products.zip(prices) productsWithPrice: Array[(String, Int)] = Array((breadsticks,4))
注意:我们使用unzip方法可以对zip后的结果反向操作:
scala> val (a,b) = productsWithPrice.unzip a: scala.collection.mutable.IndexedSeq[String] = ArrayBuffer(breadsticks) b: scala.collection.mutable.IndexedSeq[Int] = ArrayBuffer(4)
相关文章推荐
- 第十章 Scala 容器基础(二十三):使用zip合并两个集合为二元组集合
- 合并两个list数据集合
- HOW TO:在 Visual C# .NET 中使用 System.Xml 合并两个 XML 文档中的数据
- java将两个集合合并,去除重复
- linq 左连接实现两个集合的合并
- 使用 UNION 和 UNION ALL 操作符合并两个或多个 SELECT 语句的结果集
- 在单链表中将两个链表合并,合并之后的链表使用的是输入链表的节点空间,合并之后输入链表变为空表
- 使用Enumerable.SequenceEqual<TSource> 方法 (IEnumerable<TSource>, IEnumerable<TSource>)判断两个集合是否相同
- 第十章 Scala 容器基础(十七):使用filter方法过滤集合元素
- Spark学习使用笔记 - Scala篇(3)- 映射,元组
- 在单链表中将两个链表合并,合并之后的链表使用的是输入链表的节点空间,合并之后输入链表变为空表
- 写程序。设ha和hb分别是两个带头结点的非递减有序单链表的头指针,试设计算法,将这两个有序链表合并成一个非递增有序的单链表。要求使用原链表空间,
- [C#]使用Join与GroupJoin将两个集合进行关联与分组
- 两个多项式相乘 使用散列表加速 在计算时合并多项式的项
- Scala 之 合并两个map
- 两个List集合使用removeAll()方法遇到的坑,无法移除掉两个集合相同的数据。
- Path.Combine (合并两个路径字符串)方法的一些使用细节
- 第十章 Scala 容器基础(二十五):使用Range来填充一个集合
- Scala入门--集合的使用及对集合操作的函数的使用
- 在单链表中将两个链表合并,合并之后的链表使用的是输入链表的节点空间,合并之后输入链表变为空表