【问题标题】:Scala, prepend a list of variables to the beginning of each list in a listScala,将变量列表添加到列表中每个列表的开头
【发布时间】:2014-07-25 12:07:42
【问题描述】:

我是 scala 的新手,希望使用 map、flatMap 和/或理解来完成以下工作。

我有一个列表列表l = List[List[T]]。例如,l = [[1,2,3],[2,4,6,4],[3,4,6,2,3]]。请注意,l 中的每个列表都可以有不同的长度。

现在我有了val x: List[Int] = [1,2,3],我想对xl 执行一些操作,返回[[1,1,2,3], [1,2,4,6,4], [1,3,4,6,2,3], [2,1,2,3], [2,2,4,6,4], [2,3,4,6,2,3], [3,1,2,3], [3,2,4,6,4], [3,3,4,6,2,3]](子列表的顺序无关紧要)。

我觉得我应该使用 map 或 flatMap 或 for-loop 来执行此操作,但经过长时间的试验,我什至无法获得正确的类型。有人可以帮我吗?

【问题讨论】:

  • 括号通常被理解为列表,但如果这是您的实际 Scala 代码,那么您将需要使用 List(),如我的回答中所示。你的例子的类型是List[Int](1,2,3),或者只是让类型被推断出来并使用val x = List(1,2,3)

标签: list scala for-loop map flatmap


【解决方案1】:
scala> val ls = List(List(1,2,3),List(2,4,6,4),List(3,4,6,2,3))
ls: List[List[Int]] = List(List(1, 2, 3), List(2, 4, 6, 4), List(3, 4, 6, 2, 3))

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

scala> for(x <- xs; l <- ls) yield x +: l
res22: List[List[Int]] = List(List(1, 1, 2, 3), List(1, 2, 4, 6, 4), List(1, 3, 4, 6, 2, 3), List(2, 1, 2, 3), List(2, 2, 4, 6, 4), List(2, 3, 4, 6, 2, 3), List(3, 1, 2, 3), List(3, 2, 4, 6, 4), List(3, 3, 4, 6, 2, 3))

【讨论】:

    【解决方案2】:
    x.flatMap(i => l.map(i::_))
    

    【讨论】:

      猜你喜欢
      • 2015-12-16
      • 1970-01-01
      • 1970-01-01
      • 2021-01-15
      • 2016-04-04
      • 2018-03-09
      • 1970-01-01
      • 2020-06-23
      • 1970-01-01
      相关资源
      最近更新 更多