如何在根类型为List [Any]时展平列表列表

时间:2016-09-27 14:10:11

标签: scala

我有代码计算多个列表的叉积并生成列表列表,但根类型为List[Any],所以如果我尝试这样做:

val result : List[Any] = computedListOfLists() 
// result is List(List(List(0.1, 1), a), List(List(0.1, 1), b), List(List(0.1, 2), a), List(List(0.1, 2), b), List(List(0.1, 3), a), List(List(0.1, 3), b), List(List(0.01, 1), a), List(List(0.01, 1), b), List(List(0.01, 2), a), List(List(0.01, 2), b), List(List(0.01, 3), a), List(List(0.01, 3), b), List(List(0.001, 1), a), List(List(0.001, 1), b), List(List(0.001, 2), a), List(List(0.001, 2), b), List(List(0.001, 3), a), List(List(0.001, 3), b))

result.flatten // will not compile   

1 个答案:

答案 0 :(得分:5)

您不能直接使用flatten但是您可以定义这样的函数:

def flatten(l: List[Any]): List[Any] = l flatMap {
  case list: List[_] => flatten(list)
  case e => List(e)
}

并且这样打电话:

val l = List(
  List(List(0.1, 1), "a"),
  List(List(0.1, 1), "b"),
  List(List(0.1, 2), "a"),
  List(List(0.1, 2), "b"),
  List(List(0.1, 3), "a"),
  List(List(0.1, 3), "b"),
  List(List(0.01, 1), "a"),
  List(List(0.01, 1), "b"),
  List(List(0.01, 2), "a"),
  List(List(0.01, 2), "b"),
  List(List(0.01, 3), "a"),
  List(List(0.01, 3), "b"),
  List(List(0.001, 1), "a"),
  List(List(0.001, 1), "b"),
  List(List(0.001, 2), "a"),
  List(List(0.001, 2), "b"),
  List(List(0.001, 3), "a"),
  List(List(0.001, 3), "b"))

flatten(l)

结果将是:

List[Any] = List(0.1, 1.0, a, 0.1, 1.0, b, 0.1, 2.0, a, 0.1, 2.0, b, 0.1, 3.0, a, 0.1, 3.0, b, 0.01, 1.0, a, 0.01, 1.0, b, 0.01, 2.0, a, 0.01, 2.0, b, 0.01, 3.0, a, 0.01, 3.0, b, 0.001, 1.0, a, 0.001, 1.0, b, 0.001, 2.0, a, 0.001, 2.0, b, 0.001, 3.0, a, 0.001, 3.0, b)