Scala 将序列合并为三元组 [复制]

Scala Combine Sequences into triples [duplicate]

提问人:princess of persia 提问时间:2/24/2013 更新时间:2/24/2013 访问量:300

问:

我有 3 个 IndexedSequences,我想将它们组合如下:

indSeq1 = (a,b,c)
indSeq2 = (1,2,3)
indSeq3 = (!,@,#)

result:([a,1,!],[b,2,@],[c,3,#])

我使用了zipped,但我得到了如何在scala中做到这一点,我希望输出也是IndexedSequence。([a,b,c],[1,2,3],[!,@,#])

列出 Scala 字典 zip 序列

评论


答:

0赞 jonathanasdf 2/24/2013 #1

尝试在压缩后运行转置。

2赞 Daniel C. Sobral 2/24/2013 #2

这不是这样做时得到的:

scala> val indSeq1 = Seq('a', 'b', 'c')
indSeq1: Seq[Char] = List(a, b, c)

scala> val indSeq2 = Seq(1,2,3)
indSeq2: Seq[Int] = List(1, 2, 3)

scala> val indSeq3 = Seq('!', '@', '#')
indSeq3: Seq[Char] = List(!, @, #)

scala> (indSeq1, indSeq2, indSeq3).zipped
res30: scala.runtime.Tuple3Zipped[Char,Seq[Char],Int,Seq[Int],Char,Seq[Char]] = scala.runtime.Tuple3Zipped@9789aa5f

scala> res30.toSeq
res31: Seq[(Char, Int, Char)] = Stream((a,1,!), ?)

scala> res30.toList
res32: List[(Char, Int, Char)] = List((a,1,!), (b,2,@), (c,3,#))

scala> res30.toIndexedSeq
res33: scala.collection.immutable.IndexedSeq[(Char, Int, Char)] = Vector((a,1,!), (b,2,@), (c,3,#))
2赞 Eastsun 2/24/2013 #3

只需使用以下方法:invertTuple3

scala> val s1 = IndexedSeq('a', 'b', 'c')
s1: IndexedSeq[Char] = Vector(a, b, c)

scala> val s2 = Seq(1, 2, 3)
s2: Seq[Int] = List(1, 2, 3)

scala> val s3 = Seq('!, '@, '#)
s3: Seq[Symbol] = List('!, '@, '#)

scala> (s1, s2, s3).invert
res0: IndexedSeq[(Char, Int, Symbol)] = Vector((a,1,'!), (b,2,'@), (c,3,'#))