[英]Kotlin: initialize 2D array
I am in a loop, reading 2 columns from a file.我在一个循环中,从一个文件中读取 2 列。 I read R, T combinations, 50 times.我读了 R,T 组合,50 遍。 I want R and T to be in an array so I can look up the Nth pair of R, T later in a function.我希望 R 和 T 在一个数组中,这样我就可以在 function 中查找第 N 对 R, T。 How do I put the R, T pairs in an array and look up the, say, 25th entry later in a function?如何将 R、T 对放在一个数组中,然后在 function 中查找例如第 25 个条目?
For example:例如:
for (nsection in 1 until NS+1) {
val list: List<String> = lines[nsection + 1].trim().split("\\s+".toRegex())
val radius = list[0].toFloat()
println("Radius = $radius")
val twist = list[8].toFloat()
println("twist = $twist")
}
Would like to pull radius and twist pairs from a table in a function later.想稍后从 function 中的表中拉出半径和双绞线。 NS goes up to 50 so far.到目前为止,NS 上升到 50。
You can use map()
on your range iterator to produce a List of what you want.您可以在范围迭代器上使用map()
来生成您想要的列表。
val radiusTwistPairs: List<Pair<Float, Float>> = (1..NS).map { nsection ->
val list = lines[nsection + 1].trim().split("\\s+".toRegex())
val radius = list[0].toFloat()
println("Radius = $radius")
val twist = list[8].toFloat()
println("twist = $twist")
radius to twist
}
Or use an Array constructor:或者使用 Array 构造函数:
val radiusTwistPairs: Array<Pair<Float, Float>> = Array(NS) { i ->
val list = lines[i + 2].trim().split("\\s+".toRegex())
val radius = list[0].toFloat()
println("Radius = $radius")
val twist = list[8].toFloat()
println("twist = $twist")
radius to twist
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.