zoukankan      html  css  js  c++  java
  • scala 学习之:list span 用法

    Pack consecutive duplicates of list elements into sublists.
    If a list contains repeated elements they should be placed in separate sublists.
    Example:
    
    scala> pack(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e))
    res0: List[List[Symbol]] = List(List('a, 'a, 'a, 'a), List('b), List('c, 'c), List('a, 'a), List('d), List('e, 'e, 'e, 'e))

    题目描述: 如果一个list中有相同的元素,则将相同的元素放到一个新的list中,最后返回list[list]

    scala List span 函数:

    定义:

    final def span(p: (A) ⇒ Boolean): (List[A], List[A])
    Splits this list into a prefix/suffix pair according to a predicate.
    
    Note: c span p is equivalent to (but possibly more efficient than) (c takeWhile p, c dropWhile p), provided the evaluation of the predicate p does not cause any side-effects.
    returns
    a pair consisting of the longest prefix of this list whose elements all satisfy p, and the rest of this list.
    Definition Classes
    List → LinearSeqOptimized → TraversableLike → GenTraversableLike
    Annotations
    @inline()

    即span 根据输入的bool表达式,将list进行分割。返回一个list集合。但是碰到第一个不满足的元素,即返回。如:

     list 的partition: 会遍历所有元素。

    思路: 题目的要求是,连续的相等的元素放到同一个 list中,因此

    使用span 进行分割。

     def packList[T](a:List[T]): List[List[T]] = {
              def _pack(res:List[List[T]], tmp:List[T]):List[List[T]] = {
                  tmp match{
                    case Nil => res
                    case ls =>{
                        val (s:List[T], r:List[T]) = tmp span{_ == tmp.head}
                        _pack(res:::List(s), r)            
                    }
                  }
              }
              _pack(List(), a)
        }
  • 相关阅读:
    Mbps、Kbps、bps、kb、mb区别和换算
    Python导入模块方法
    C# WinForm 程序免安装 .NET Framework(XP/win7/win10环境运行)
    生成缩略图
    WCF 的优势和特点
    不要在using语句中调用WCF服务
    pb getchild获取DropDownDW子窗体后进行取值
    Bootstrap后台管理模板调研
    PB调用C#编写的DLL
    PowerBuilder与嵌入浏览器交互
  • 原文地址:https://www.cnblogs.com/missmzt/p/6031324.html
Copyright © 2011-2022 走看看