Scala 分区/收集用法
是否可以使用一次 collect
调用来创建 2 个新列表?如果没有,我该如何使用partition
来做到这一点?
Is it possible to use one call to collect
to make 2 new lists? If not, how can I do this using partition
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
collect
(定义于 TraversableLike 并在所有子类中可用)可与集合和PartialFunction
配合使用。碰巧的是,大括号内定义的一堆 case 子句是一个部分函数(请参阅 Scala 语言规范 [警告 - PDF])与异常处理一样:
这是定义仅接受的函数的便捷方法给定类型的一些值。
考虑在混合值列表上使用它:
collect
方法的参数是PartialFunction[Any,String]
。PartialFunction
因为它没有为Any
类型(即List
的类型)和String
类型的所有可能输入定义> 因为这就是所有子句返回的内容。如果您尝试使用
map
而不是collect
,则mixedList
末尾的双精度值将导致MatchError
>。使用collect
只会丢弃此值以及未定义 PartialFunction 的任何其他值。一种可能的用途是将不同的逻辑应用于列表的元素:
虽然这只是一个示例,但使用这样的可变变量被许多人认为是一种战争犯罪 - 所以请不要这样做!
一个更好的解决方案是使用两次collect:
或者如果您确定列表只包含两种类型的值,您可以使用
partition
,它将集合分成值取决于它们是否匹配某个谓词:这里的问题是
strings
和ints
都是List[Any]
类型,尽管您可以轻松地将它们强制返回到更类型安全的东西(也许通过使用collect
...)如果您已经有一个类型安全的集合并且想要拆分元素的某些其他属性,那么事情就是对您来说更容易一些:
希望总结这两种方法可以帮助您!
collect
(defined on TraversableLike and available in all subclasses) works with a collection and aPartialFunction
. It also just so happens that a bunch of case clauses defined inside braces are a partial function (See section 8.5 of the Scala Language Specification [warning - PDF])As in exception handling:
It's a handy way to define a function that will only accept some values of a given type.
Consider using it on a list of mixed values:
The argument to to
collect
method is aPartialFunction[Any,String]
.PartialFunction
because it's not defined for all possible inputs of typeAny
(that being the type of theList
) andString
because that's what all the clauses return.If you tried to use
map
instead ofcollect
, the the double value at the end ofmixedList
would cause aMatchError
. Usingcollect
just discards this, as well as any other value for which the PartialFunction is not defined.One possible use would be to apply different logic to elements of the list:
Although this is just an example, using mutable variables like this is considered by many to be a war crime - So please don't do it!
A much better solution is to use collect twice:
Or if you know for certain that the list only contains two types of values, you can use
partition
, which splits a collections into values depending on whether or not they match some predicate:The catch here is that both
strings
andints
are of typeList[Any]
, though you can easily coerce them back to something more typesafe (perhaps by usingcollect
...)If you already have a type-safe collection and want to split on some other property of the elements, then things are a bit easier for you:
Hope that sums up how the two methods can help you out here!
不知道如何在不使用可变列表的情况下使用
collect
来做到这一点,但是partition
也可以使用模式匹配(只是更详细一点)Not sure how to do it with
collect
without using mutable lists, butpartition
can use pattern matching as well (just a little more verbose)通常使用的
collect
的签名,例如Seq
,实际上是一个特殊情况
所以如果你在默认模式下使用它,答案是否定的,当然不是:你从中得到了一个序列。如果您按照
CanBuildFrom
到Builder
,您会发现可以使That
实际上成为两个序列,但它无法被告知一个项目应该进入哪个序列,因为部分函数只能说“是,我属于”或“不,我不属于”。那么,如果您想要多个条件导致您的列表被分成一堆不同的部分,您该怎么办?一种方法是创建一个指标函数
A => Int
,其中您的A
映射到编号类,然后使用groupBy
。例如:现在您可以按类别(在本例中为 0、1 和 2)查找子列表。不幸的是,如果您想忽略某些输入,您仍然必须将它们放入一个类中(例如,在这种情况下您可能不关心
None
的多个副本)。The signature of the normally-used
collect
on, say,Seq
, iswhich is really a particular case of
So if you use it in default mode, the answer is no, assuredly not: you get exactly one sequence out from it. If you follow
CanBuildFrom
throughBuilder
, you see that it would be possible to makeThat
actually be two sequences, but it would have no way of being told which sequence an item should go into, since the partial function can only say "yes, I belong" or "no, I do not belong".So what do you do if you want to have multiple conditions that result in your list being split into a bunch of different pieces? One way is to create an indicator function
A => Int
, where yourA
is mapped into a numbered class, and then usegroupBy
. For example:Now you can look up your sub-lists by class (0, 1, and 2 in this case). Unfortunately, if you want to ignore some inputs, you still have to put them in a class (e.g. you probably don't care about the multiple copies of
None
in this case).我用这个。它的一大好处是它在一次迭代中结合了分区和映射。一个缺点是它确实分配了一堆临时对象(
Either.Left
和Either.Right
实例)I use this. One nice thing about it is it combines partitioning and mapping in one iteration. One drawback is that it does allocate a bunch of temporary objects (the
Either.Left
andEither.Right
instances)从 Scala 2.13 开始,大多数集合现在都提供了
partitionMap< /code>
方法,根据返回
Right
或Left
的函数对元素进行分区。这允许我们根据类型(作为一个
collect
允许在分区列表中具有特定类型)或任何其他模式进行模式匹配:Starting in
Scala 2.13
, most collections are now provided with apartitionMap
method which partitions elements based on a function which returns eitherRight
orLeft
.That allows us to pattern match based on the type (which as a
collect
enables having specific types in the partitioned lists) or any other pattern:我在这里找不到这个基本问题的令人满意的解决方案。
我不需要关于
collect
的讲座,也不在乎这是否是某人的作业。另外,我不想要只适用于List
的东西。这是我的尝试。高效且与任何
TraversableOnce
兼容,甚至是字符串:用法示例:
I could not find a satisfying solution to this basic problem here.
I don't need a lecture on
collect
and don't care if this is someone's homework. Also, I don't want something that works only forList
.So here is my stab at it. Efficient and compatible with any
TraversableOnce
, even strings:Example usages:
像这样的东西可能会有所帮助
称其为
中的 API 类似
Advantage 是一个简单的 API,与 Scala 2.12 Disadvantage ;集合运行了两次并且缺少对 CanBuildFrom 的支持
Something like this could help
To call it
Advantage is a simple API, similar with the one from Scala 2.12
Disadvantage; collection is ran twice and missing support for
CanBuildFrom
我个人会为此使用foldLeft 或foldRight。与这里的其他一些答案相比,它有几个优点。没有使用 var,所以这是一个纯函数(如果你关心这种类型的事情)。仅遍历列表一次。不创建任何无关的 Either 对象。
折叠的想法是将列表转换为单一类型。然而,没有什么可以阻止我们让这个单一类型成为任意数量列表的元组。
此示例将一个列表转换为三个不同的列表:
I would personally use a foldLeft or foldRight for this. It has a couple advantages over the some of the other answers here. No use of var, so this is a pure function (if you care about that type of thing). Only one traversal through the list. Does not create any extraneous Either objects.
The idea of a fold is to convert a list into a single type. However, nothing is stopping us from having this single type be a Tuple of any number of lists.
This example converts a list into three different lists: