如何检查列表中的所有元素是否为数字?

Kun*_*mar 2 scala

我有这种形式的数据,这基本上是一个巨大的数据.

val data: Array[(Int, Iterable[String])] =
  Array(
    (34,List("sdkfj",7, 2, 5, 3, 1, 9, 2, 1, 4)),
    (4,List(7, 14, 4, 5, 11, 9, 5, 4, 1))
  )
Run Code Online (Sandbox Code Playgroud)

我想isNumeric在可迭代项上应用一个函数,该函数应该按以下方式返回输出

Array((34,false), (4,true))
Run Code Online (Sandbox Code Playgroud)

基本上,我想要false列表中的if元素不是数字,否则true.

我试过这个功能

def isNumeric(input: String): Boolean = input.forall(_.isDigit)
Run Code Online (Sandbox Code Playgroud)

但在这种情况下,我得到一个布尔列表,而我想要整个列表的单个布尔结果.

Mar*_*rth 5

你需要调用.forall内部列表:

scala> def isNumeric(input: String): Boolean = input.forall(_.isDigit)
isNumeric: (input: String)Boolean

scala> val a:Array[(Int,List[String])] = Array((34,List("sdkfj","7", "2", "5", "3", "1", "9", "2", "1", "4")), (4,List("7", "14", "4", "5", "11", "9", "5", "4", "1")))
a: Array[(Int, List[String])] = Array((34,List(sdkfj, 7, 2, 5, 3, 1, 9, 2, 1, 4)),
                                      (4, List(7, 14, 4, 5, 11, 9, 5, 4, 1)))

scala> a.map { case (k, l) => (k, l.forall(isNumeric)) }
res0: Array[(Int, Boolean)] = Array((34,false), (4,true))
Run Code Online (Sandbox Code Playgroud)

编辑

如果要跳过某些元素的验证,可以在使用.filter之前使用.forall(仅在子列表上运行验证):

scala> val a:Array[(Int,List[String])] = Array((34,List("NA","7", "3")))
a: Array[(Int, List[String])] = Array((34,List(NA, 7, 3)))

// Not sure what an NA is, so...
scala> def isNA(s:String) = s == "NA"
isNA: (s: String)Boolean

// Using .filterNot here since you want to exclude all `NA`s
// You can also use .filter(!isNA(_)) 
// or .withFilter(!isNA(_)) which should be faster/more efficient
scala> a.map{ case (k, l) => (k, l.filterNot(isNA).forall(isNumeric)) }
res0: Array[(Int, Boolean)] = Array((34,true))
Run Code Online (Sandbox Code Playgroud)

请注意,您也可以将.isNumeric方法更改为.isNumericOrNA(从而省略a filter),尽管可能有点令人困惑,具体取决于具体NA情况.

注:参见斯卡拉API的之间的差异的说明.filter.withFilter.