斯卡拉嵌套数组扁平化 [英] Scala nested arrays flattening
问题描述
如何扁平化任意深度嵌套数组的数组?
How to flatten an array of nested arrays of any depth ?
例如
val in = Array( 1, Array(2,3), 4, Array(Array(5)) )
将被夷为平地上
val out = Array(1,2,3,4,5)
先谢谢了。
推荐答案
如果您有混合内部
和数组[INT]
,这是不是一开始就有一个非常好的主意,你可以做这样的事情。
If you have mixed Int
and Array[Int]
, which is not a very good idea to begin with, you can do something like
in.flatMap{ case i: Int => Array(i); case ai: Array[Int] => ai }
(它会抛出一个异常,如果你已经把别的东西阵列中)。因此,您可以使用它作为一个递归函数的基础上:
(it will throw an exception if you've put something else in your array). You can thus use this as the basis of a recursive function:
def flatInt(in: Array[Any]): Array[Int] = in.flatMap{
case i: Int => Array(i)
case ai: Array[Int] => ai
case x: Array[_] => flatInt(x.toArray[Any])
}
如果你不知道你在你的嵌套数组已经得到了什么,你可以替换上面内部
S按任何
和撒气数组[任何]
作为一个结果。 (编辑:在任何
情况,则需要进入最后一个)
If you don't know what you've got in your nested arrays, you can replace the above Int
s by Any
and get a flat Array[Any]
as a result. ( the Any
case then needs to go last.)
(注意:这是不是尾递归,所以它可以使栈溢出,如果你的阵列嵌套非常深。)
(Note: this is not tail-recursive, so it can overflow the stack if your arrays are nested extremely deeply.)
这篇关于斯卡拉嵌套数组扁平化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!