如何在Scala中展平不同类型的列表? [英] How to flatten a List of different types in Scala?

查看:74
本文介绍了如何在Scala中展平不同类型的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有4个元素:List[List[Object]](每个元素中的对象不同),我想要压缩,这样我就可以拥有一个List[List[obj1],List[obj2],List[obj3],List[obj4]]

I have 4 elements:List[List[Object]] (Objects are different in each element) that I want to zip so that I can have a List[List[obj1],List[obj2],List[obj3],List[obj4]]

我尝试压缩它们,并获得了一个嵌套列表,我不能对其进行扁平化处理,因为它说:没有与参数类型匹配的隐式参数.

I tried to zip them and I obtained a nested list that I can't apply flatten to because it says: no implicit argument matching parameter type.

我该如何解决?我应该尝试另一种方法还是有什么方法可以使拼合工作正常?

How can I solve this? should I try another way or is there any way to make the flatten work?

我是Scala的新手,所以这可能是一个愚蠢的问题:D 提前致谢! 克劳

I'm kinda new to scala so it may be a dumb question :D Thanks in advance! clau

推荐答案

对于一个嵌套列表: flatten将执行以下操作:

For One Nested List: flatten will do:

scala> List(List(1), List(2), List(3)).flatten
res4: List[Int] = List(1, 2, 3)

scala> List(List(List(1)), List(List(2)), List(List(3))).flatten
res5: List[List[Int]] = List(List(1), List(2), List(3))

对于多个嵌套列表,您可以:

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

val k = List(1, List(2, 3), List(List(List(List(4)), List(5)), List(6, 7)), 8)
flatten(k)

它打印List[Any] = List(1, 2, 3, 4, 5, 6, 7, 8)

这篇关于如何在Scala中展平不同类型的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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