Scala for 同时循环遍历两个列表 [英] Scala for loop over two lists simultaneously

查看:109
本文介绍了Scala for 同时循环遍历两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 List[Message] 和一个 List[Author],它们具有相同数量的项目,并且应该排序,以便在每个索引处,Message 来自 Author.

I have a List[Message] and a List[Author] which have the same number of items, and should be ordered so that at each index, the Message is from the Author.

我还有一个类,我们在这里称之为 SmartMessage,它的构造函数带有 2 个参数:一个 Message 和相应的 Author.

I also have class that we'll call here SmartMessage, with a constructor taking 2 arguments: a Message and the corresponding Author.

我想要做的是创建一个List[SmartMessage],结合2个简单列表的数据.

What I want to do, is to create a List[SmartMessage], combining the data of the 2 simple lists.

额外问题:List 在 Scala 中是否保留插入顺序?只是为了确保我创建了具有相同顺序的 List[Message] 和一个 List[Author].

Extra question: does List preserve insertion order in Scala? Just to make sure I create List[Message] and a List[Author] with same ordering.

推荐答案

你可以使用 zip:

val ms: List[Message] = ???
val as: List[Author] = ???

var sms = for ( (m, a) <- (ms zip as)) yield new SmartMessage(m, a)

如果你不喜欢for-comprehensions,你可以使用map:

If you don't like for-comprehensions you could use map:

var sms = (ms zip as).map{ case (m, a) => new SmartMessage(m, a)}

方法 zip 创建对的集合.在这种情况下 List[(Message, Author)].

Method zip creates collection of pairs. In this case List[(Message, Author)].

您也可以在 Tuple2(以及 Tuple3)上使用 zipped 方法:

You could also use zipped method on Tuple2 (and on Tuple3):

var sms = (ms, as).zipped.map{ (m, a) => new SmartMessage(m, a)}

如您所见,在这种情况下,您不需要 map 中的模式匹配.

As you can see you don't need pattern matching in map in this case.

额外

ListSeq 并且 Seq 保留顺序.请参阅 scala 集合概览.

List is Seq and Seq preserves order. See scala collections overview.

集合有 3 个主要分支:SeqSet 和 地图.

There are 3 main branches of collections: Seq, Set and Map.

  • Seq 保留元素的顺序.
  • Set 不包含重复元素.
  • Map 包含从键到值.
  • Seq preserves order of elements.
  • Set contains no duplicate elements.
  • Map contains mappings from keys to values.

Listlinked list,所以你应该在前面加上元素,而不是追加.请参阅 性能特征 scala 集合.

List in scala is linked list, so you should prepend elements to it, not append. See Performance Characteristics of scala collections.

这篇关于Scala for 同时循环遍历两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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