我正在尝试将一个Long转换为一个List[Int],其中列表中的每一项都是原始长的一个数字。
scala> val x: Long = 123412341L
x: Long = 123412341
scala> x.toString.split("").toList
res8: List[String] = List("", 1, 2, 3, 4, 1, 2, 3, 4, 1)
scala> val desired = res8.filterNot(a => a == "")
desired: List[String] = List(1, 2, 3, 4, 1, 2, 3, 4, 1)使用split("")会产生一个""列表元素,这是我最初不想要的。
我可以简单地过滤它,但是我是否有可能更干净地从123412341L到List(1, 2, 3, 4, 1, 2, 3, 4, 1)呢?
发布于 2014-03-30 23:31:22
如果您想要数字的整数值,可以这样做:
scala> x.toString.map(_.asDigit).toList
res65: List[Int] = List(1, 2, 3, 4, 1, 2, 3, 4, 1)请注意.map(_.asDigit)所产生的差异:
scala> x.toString.toList
res67: List[Char] = List(1, 2, 3, 4, 1, 2, 3, 4, 1)
scala> res67.map(_.toInt)
res68: List[Int] = List(49, 50, 51, 52, 49, 50, 51, 52, 49)x.toString.toList是一个字符列表,即List('1','2','3',...)。列表的toString呈现使它看起来是一样的,但两者是完全不同的--例如,一个'1‘字符的整数值为49。您应该使用的数字取决于您是否需要数字字符或它们所代表的整数。
发布于 2014-03-30 23:50:25
正如Alexey在下面指出的,这段代码存在严重问题:\不要使用它。
不使用字符串转换:
def splitDigits(n:Long): List[Int] = {
n match {
case 0 => List()
case _ => {
val onesDigit = (n%10)
splitDigits((n-onesDigit)/10) ++ List( onesDigit.toInt )
}
}
}给予:
splitDigits(123456789) //> res0: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
splitDigits(1234567890) //> res1: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
splitDigits(12345678900L) //> res2: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0)该函数不是尾递归函数,但对于长值,它应该工作得很好:
splitDigits(Long.MaxValue) //> res3: List[Int] = List(9, 2, 2, 3, 3, 7, 2, 0, 3, 6, 8, 5, 4, 7, 7, 5, 8, 0, 7)发布于 2014-03-30 22:55:30
快一点,有点烦躁:
x.toString.map(_.toString.toInt).toListhttps://stackoverflow.com/questions/22750852
复制相似问题