Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将一个列表拆分为多个列表避免scala中的强制方法_Scala - Fatal编程技术网

如何将一个列表拆分为多个列表避免scala中的强制方法

如何将一个列表拆分为多个列表避免scala中的强制方法,scala,Scala,在一个场景中,我必须迭代一个列表,然后根据列表中的对象生成多个列表,如果不使用命令式方法,我就无法理解如何做到这一点。更具体地说,假设我有一个项目列表[a、b、c、d],并希望根据项目的不同属性生成三个新列表: [a1,b1,c1,d1],[a2,b2,c2,d2],[a3,b3,c3,d3] 我在下面给出了一个简单的例子,这可能是我在java中应该如何做到的,但是我想知道是否有人可以推荐一种方法来做到这一点,同时避免使用命令式风格 case class Atom(nuc: Int, prot:

在一个场景中,我必须迭代一个列表,然后根据列表中的对象生成多个列表,如果不使用命令式方法,我就无法理解如何做到这一点。更具体地说,假设我有一个项目列表[a、b、c、d],并希望根据项目的不同属性生成三个新列表: [a1,b1,c1,d1],[a2,b2,c2,d2],[a3,b3,c3,d3]

我在下面给出了一个简单的例子,这可能是我在java中应该如何做到的,但是我想知道是否有人可以推荐一种方法来做到这一点,同时避免使用命令式风格

case class Atom(nuc: Int, prot: Int, neut: Int)

class Splitter(list: Array[Atom]) {

    val nucs: ArrayBuffer[(Int, Int)] = ArrayBuffer()
    val prots: ArrayBuffer[(Int, Int)] = ArrayBuffer()
    val neuts: ArrayBuffer[(Int, Int)] = ArrayBuffer()

    list foreach { atom =>
        nucs += (atom.nuc -> atom.nuc * 3)
        prots += (atom.prot -> atom.prot * 4)
        neuts += (atom.neut -> atom.neut * 5)
    }
}
试试这个:

val (nucs, prots, neuts) =
  list.map(atom => (atom.nuc*3, atom.prot*4, atom.neut*5)).unzip3

我认为拆分是使用一些标准将集合划分为更小的集合。你想将你的集合转换成三个其他集合,而不是分裂:如果你想在一个特性中要拆分集合,考虑使用<代码> GROPBI< <代码>函数,见下面的例子:<代码>列表(1,2,3,4,5,6,7,8,9,10)。GROUPBY {案例项IF(项目% 2=0)=>“偶数”情况项IF(项目% 2=1)=“奇数”}
res0:scala.collection.immutable.Map[String,List[Int]=Map(奇数->列表(1,3,5,7,9),偶数->列表(2,4,6,8,10))