代码之家  ›  专栏  ›  技术社区  ›  user79074

如何将一个列表拆分为多个列表,避免scala中的命令式方法

  •  0
  • user79074  · 技术社区  · 11 年前

    在一个场景中,我必须迭代一个列表,并从中根据列表中的对象生成多个列表,如果不避免使用命令式方法,我就无法弄清楚如何做到这一点。更具体地说,我有一个项目列表[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)
        }
    }
    
    1 回复  |  直到 11 年前
        1
  •  0
  •   Marius Danila    11 年前

    试试这个:

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