scala:产生两个循环的成对组合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11721829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:24:07  来源:igfitidea点击:

scala: yield pairwise combinations of two loops

scala

提问by Jakub M.

I would like to create a collection with tuples containing all pairwise combinations of two lists. Something like:

我想创建一个包含两个列表的所有成对组合的元组的集合。就像是:

for ( x <- xs )
  for ( y <- ys ) 
    yield (x,y)

In Python this would work, in Scala apparently foryields only for the last loop (so this evaluates to Unit)

在 Python 中这是可行的,在 Scala 中显然for只在最后一个循环中产生(因此计算结果为Unit

What is the cleanest way to implement it in Scala?

在 Scala 中实现它的最简洁的方法是什么?

回答by Nicolas

You were almost there:

你快到了:

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

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

scala> for (x <- xs; y <- ys) yield (x,y)
res3: List[(Int, Int)] = List((1,4), (1,5), (1,6), (2,4), (2,5), (2,6), (3,4), (3,5), (3,6))

回答by tgr

A little bit more explicit according to Nicolas:
In Scala you can use multiple generators in a single for-comprehension.

根据 Nicolas 的说法更明确一点:
在 Scala 中,您可以在单个 for-comprehension 中使用多个生成器。

val xs = List(1,2,3)
val ys = List(4,5)

for {
  x <- xs
  y <- ys
} yield (x,y)

res0: List[(Int, Int)] = List((1,4), (1,5), (2,4), (2,5), (3,4), (3,5))

You can even evaluate in the comprehension.

您甚至可以在理解中进行评估。

for {
  x <- xs
  y <- ys
  if (x + y == 6)
} yield (x,y)

res1: List[(Int, Int)] = List((1,5), (2,4))

Or make an assignment.

或者做一个任务。

for {
  x <- xs
  y <- ys
  val z = x + y
} yield (x,y,z)

res2: List[(Int,Int,Int)] = List((1,4,5), (1,5,6), (2,4,6), (2,5,7), (3,4,7), (3,5,8))