scala序列组合

时间:2018-04-01 00:56:34

标签: scala functional-programming

我怎么能这样平顶:

(Seq(1,2,3,4,5), 
  Seq(Seq(1.0, 2.0, 3.0, 4.0, 5.0),
    Seq(1.0, 2.0, 3.0, 4.0, 5.0), 
    Seq(1.0, 2.0, 3.0, 4.0, 5.0)), 
  Seq("a", "b", "c"))
  .zipped.map((a,b,c) => (a,b,c))

而不是接收:

List((1,List(1.0, 2.0, 3.0, 4.0, 5.0),a), (2,List(1.0, 2.0

得到:

List((1,List(1.0),a), (1,List(2.0),a)(1,List(3.0),a)(1,List(4.0),a)(1,List(5.0),a)(2,List(1.0, 2.0

1 个答案:

答案 0 :(得分:2)

你的意思是?

val s = (Seq(1,2,3,4,5), 
  Seq(Seq(1.0, 2.0, 3.0, 4.0, 5.0),
    Seq(1.0, 2.0, 3.0, 4.0, 5.0), 
    Seq(1.0, 2.0, 3.0, 4.0, 5.0)), 
  Seq("a", "b", "c"))
  .zipped
  .flatMap{ case (n, seq, c) =>
    seq.map(s => (n, List(s), c))
  }

println(s)

生成以下输出(直到缩进):

List(
  (1,List(1.0),a), (1,List(2.0),a), (1,List(3.0),a), (1,List(4.0),a), (1,List(5.0),a), 
  (2,List(1.0),b), (2,List(2.0),b), (2,List(3.0),b), (2,List(4.0),b), (2,List(5.0),b), 
  (3,List(1.0),c), (3,List(2.0),c), (3,List(3.0),c), (3,List(4.0),c), (3,List(5.0),c)
)

请注意,以下更短且更清晰的for - 理解产生完全相同的输出:

for {
  (n, c) <- Seq(1, 2, 3) zip Seq("a", "b", "c")
  s <- Seq(1.0, 2.0, 3.0, 4.0, 5.0)
} yield {
  (n, List(s), c)
}