Scala for 同时循环遍历两个列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17199534/
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
Scala for loop over two lists simultaneously
提问by Blackbird
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 Messageis from the Author.
我有 aList[Message]和 a List[Author],它们具有相同数量的项目,并且应该进行排序,以便在每个索引处,Message都来自Author.
I also have class that we'll call here SmartMessage, with a constructor taking 2 arguments: a Messageand the corresponding Author.
我还有一个类,我们将在这里调用它SmartMessage,构造函数带有 2 个参数:aMessage和相应的Author.
What I want to do, is to create a List[SmartMessage], combining the data of the 2 simple lists.
我想要做的是创建一个List[SmartMessage],结合两个简单列表的数据。
Extra question: does Listpreserve insertion order in Scala? Just to make sure I create List[Message]and a List[Author]with same ordering.
额外的问题:List在 Scala 中是否保留插入顺序?只是为了确保我创建List[Message]并List[Author]具有相同的顺序。
回答by senia
You could use zip:
你可以使用zip:
val ms: List[Message] = ???
val as: List[Author] = ???
var sms = for ( (m, a) <- (ms zip as)) yield new SmartMessage(m, a)
If you don't like for-comprehensionsyou could use map:
如果你不喜欢for-comprehensions你可以使用map:
var sms = (ms zip as).map{ case (m, a) => new SmartMessage(m, a)}
Method zipcreates collection of pairs. In this case List[(Message, Author)].
方法zip创建对的集合。在这种情况下List[(Message, Author)]。
You could also use zippedmethod on Tuple2(and on Tuple3):
您还可以zipped在Tuple2(和Tuple3)上使用方法:
var sms = (ms, as).zipped.map{ (m, a) => new SmartMessage(m, a)}
As you can see you don't need pattern matching in mapin this case.
如您所见,map在这种情况下您不需要模式匹配。
Extra
额外的
Listis Seqand Seqpreserves order. See scala collections overview.
List是Seq并Seq保持秩序。请参阅scala 集合概述。
There are 3 main branches of collections: Seq, Setand Map.
- Seqpreserves order of elements.
- Setcontains no duplicate elements.
- Mapcontains mappings from keys to values.
Listin scala is linked list, so you should prepend elements to it, not append. See Performance Characteristicsof scala collections.

