为什么列表分区有效而跨度无效 [英] Why List partition works while span does not

查看:42
本文介绍了为什么列表分区有效而跨度无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 List oX of (Char, Int) pars(它包含只有唯一 Char 值的对)

I have this List oX of (Char, Int) pars (it contains pairs with only unique Char values)

List(( ,3), (d,1), (e,3), (h,3), (i,1) , (l,3), (o,2), (r,2), (t,1), (w,1))

我需要将这个列表分成 2 个 - 一个包含任何具有 'd' Char 的对,另一个是其余的.

I need to partition this list into 2 - one that contains any pair that has 'd' Char and another is the rest.

所以我尝试了分区和跨度,但发现跨度没有按预期工作.这是结果(从 Scala 工作表复制)

So I tried partition and span but found that span does not work as expected. Here are the results (copied from scala worksheet)

 val myPartition = oX.partition(e => e._1 == 'd') > myPartition  : (List[(Char, Int)], List[(Char, Int)]) = (List((d,1)),List(( ,3), (e,3), (h,3), (i,1), (l,3), (o,2), (r,2), (t,1), (w,1)))

  val mySpan = oX.span(e => e._1 == 'd') > mySpan  : (List[(Char, Int)], List[(Char, Int)]) = (List(),List(( ,3), (d,1), (e,3), (h,3), (i,1), (l,3), (o,2), (r,2), (t,1), (w,1)))

我很困惑为什么给定相同的谓词functino分区给我预期的结果而span给我空列表作为第一个列表和原始副本作为第二个列表

I am puzzled why given same predicate functino partition gives me expected result while span gives me empty List as first list and copy of original as second list

推荐答案

来自 documentation of span: "返回列表的最长前缀,其元素都满足给定的谓词,以及列表的其余部分."

From the documentation of span: "Returns the longest prefix of the list whose elements all satisfy the given predicate, and the rest of the list."

所以这里 span 给了你预期的结果:因为你的列表中的第一个元组没有字符 d,列表中每个元组的最长前缀有字符 d 确实是空列表.

So here span gives you the expected result: since the first tuple in your list doesn't have the character d, the longest prefix of the list where each tuple has the character d is indeed the empty list.

这篇关于为什么列表分区有效而跨度无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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