如何在 Scala 中将范围转换为列表或数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5612932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert Range to List or Array in Scala
提问by Loic
I want to convert a range of Int into a a List or an Array. I have this code working in Scala 2.8:
我想将一系列 Int 转换为列表或数组。我有这段代码在 Scala 2.8 中工作:
var years: List[Int] = List()
val firstYear = 1990
val lastYear = 2011
firstYear.until(lastYear).foreach(
e => years = years.:+(e)
)
I would like to know if there is another syntax possible, to avoid using foreach, I would like to have no loop in this part of code.
我想知道是否有另一种可能的语法,以避免使用 foreach,我想在这部分代码中没有循环。
Thanks a lot!
非常感谢!
Loic
洛伊克
回答by tenshi
You can use toListmethod:
您可以使用toList方法:
scala> 1990 until 2011 toList
res2: List[Int] = List(1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010)
toArraymethod converts Rangeto array.
toArray方法转换Range为数组。
回答by Daniel C. Sobral
And there's also this, in addition to the other answers:
除了其他答案之外,还有这个:
List.range(firstYear, lastYear)
回答by RoToRa
Rangehas a toListand a toArraymethod:
Range有toList一个toArray方法:
firstYear.until(lastYear).toList
firstYear.until(lastYear).toArray
回答by shellholic
Simply:
简单地:
(1990 until 2011).toList
but don't forget that untildoes notinclude the last number (stops at 2010). If you want 2011, use to:
但不要忘了,until它不包括最后一个数(2010年停止)。如果你想要 2011,请使用to:
(1990 to 2011).toList

