使用4(或N)个集合一次只能产生一个值(1xN)(即压缩为tuple4 +) [英] Use 4 (or N) collections to yield only one value at a time (1xN) (i.e. zipped for tuple4+)

查看:144
本文介绍了使用4(或N)个集合一次只能产生一个值(1xN)(即压缩为tuple4 +)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

scala> val a = List(1,2)
a: List[Int] = List(1, 2)

scala> val b = List(3,4)
b: List[Int] = List(3, 4)

scala> val c = List(5,6)
c: List[Int] = List(5, 6)

scala> val d = List(7,8)
d: List[Int] = List(7, 8)

scala> (a,b,c).zipped.toList
res6: List[(Int, Int, Int)] = List((1,3,5), (2,4,6))

现在:

scala> (a,b,c,d).zipped.toList
<console>:12: error: value zipped is not a member of (List[Int], List[Int], List[Int],     List[Int])
              (a,b,c,d).zipped.toList
                       ^

我在其他地方搜索过,包括 this one < a>和这一个,但没有结论性答案。

I've searched for this elsewhere, including this one and this one, but no conclusive answer.

我想要执行以下操作或类似操作:

I want to do the following or similar:

for((itemA,itemB,itemC,itemD) <- (something)) yield itemA + itemB + itemC + itemD

有任何建议吗?

推荐答案

简短答案:

for (List(w,x,y,z) <- List(a,b,c,d).transpose) yield (w,x,y,z)
  // List[(Int, Int, Int, Int)] = List((1,3,5,7), (2,4,6,8))

为什么你想要他们作为元组,我不知道,但更有趣的情况下,当你的列表是不同的类型,例如,你想将它们组合成一个对象列表: / p>

Why you want them as tuples, I'm not sure, but a slightly more interesting case would be when your lists are of different types, and for example, you want to combine them into a list of objects:

case class Person(name: String, age: Int, height: Double, weight: Double)
val names =   List("Alf", "Betty")
val ages =    List(22, 33)
val heights = List(111.1, 122.2)
val weights = List(70.1, 80.2)
val persons: List[Person] = ???

解决方案1:使用 transpose

for { List(name: String, age: Int, height: Double, weight: Double) <- 
        List(names, ages, heights, weights).transpose
    } yield Person(name, age, height, weight)

这里,我们需要List提取器中的类型注解,因为 transpose 给出一个 List [List [Any] ]

Here, we need the type annotations in the List extractor, because transpose gives a List[List[Any]].

解决方案2:使用迭代器:

Solution 2: using iterators:

val namesIt   = names.iterator
val agesIt    = ages.iterator
val heightsIt = heights.iterator
val weightsIt = weights.iterator

for { name <- names } 
  yield Person(namesIt.next, agesIt.next, heightsIt.next, weightsIt.next)

有些人会避免迭代器,因为它们涉及可变状态,因此不是功能。但是如果你来自Java世界,如果你实际上已经有迭代器(输入流等),它们很容易理解。

Some people would avoid iterators because they involve mutable state and so are not "functional". But they're easy to understand if you come from the Java world and might be suitable if what you actually have are already iterators (input streams etc).

这篇关于使用4(或N)个集合一次只能产生一个值(1xN)(即压缩为tuple4 +)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆