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

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

Scala for loop over two lists simultaneously

scalascala-collections

提问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):

您还可以zippedTuple2(和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.

ListSeqSeq保持秩序。请参阅scala 集合概述

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

集合有 3 个主要分支:SeqSetMap

  • Seqpreserves order of elements.
  • Setcontains no duplicate elements.
  • Mapcontains mappings from keys to values.
  • Seq保留元素的顺序。
  • 集合不包含重复元素。
  • Map包含从键到值的映射。

Listin scala is linked list, so you should prepend elements to it, not append. See Performance Characteristicsof scala collections.

List在 scala 中是链表,所以你应该在它前面添加元素,而不是附加。请参阅Scala 集合的性能特征