我有以下val list = listOf(1, 2, 3, null, null, 6, 7)我想為以下結果填充空值:listOf(1, 2, 3, 4, 5, 6, 7)
我在 Kotlin 中找不到任何方法,你們有想法嗎?
編輯:我正在添加更多細節,串列將始終有一個開始元素和一個結束元素(即沒有串列作為listOf(null, 2 ,3)or listOf(1, 2, null))我對此進行預處理。
在我的示例中,我給出了 Integer 元素,但它可以是 Float 或 Double
uj5u.com熱心網友回復:
我設法做了一個可以插值的簡單函式。有改進的余地。
private fun Double.format(): String = DecimalFormat("#.##").format(this)
private fun List<*>.findNonNullIndex(currentIndex: Int, ascending: Boolean = true): Int {
for (i in currentIndex..lastIndex step if(ascending) 1 else -1) {
if(getOrNull(i) != null) return i
}
return currentIndex
}
fun interpolate(list: MutableList<Double>) {
println("initial : $list")
list.forEachIndexed { index, i ->
if(i == null) {
val nonNullIndex = list.findNonNullIndex(index)
val difference = list[nonNullIndex]?.minus(list[index-1] ?: return) ?: return
val coefficient = difference.div((nonNullIndex - index) 1)
for(j in index until nonNullIndex) {
list[j] = (list[j-1]?.plus(coefficient))?.format()?.toDouble()
}
}
}
println("result: $list")
}
interpolate(mutableListOf(1.0, null, null, null, 1.4, null, 1.5, 1.7))
鏈接:https ://pl.kotl.in/HcqoB8qFL
uj5u.com熱心網友回復:
試試這個
inline fun <T>List<T?>.replaceIfNull(block:(T) -> T) : List<T>{
val temp = mutableListOf<T>()
for((index, element) in this.withIndex()){
if(element == null){
temp.add(block(this[index - 1] ?: temp[index - 1]))
} else {
temp.add(element)
}
}
return temp
}
fun main() {
val list = listOf(1, 2, 3, null, null, 6, 7)
val foo = list.replaceIfNull { nonNullValue ->
nonNullValue 1
}
println(foo) // [1, 2, 3, 4, 5, 6, 7]
}
編輯
線性模型
fun <T:Number>List<T?>.interpolate() : List<Double> {
val temp = mutableListOf<Double>()
var nullCounter = 0
this.forEach { element ->
if(element != null){
val formatedElement = element.format()
temp.add(formatedElement)
if(nullCounter > 0){
var difference = (formatedElement - temp[temp.size - 2]) / (nullCounter 1)
for(i in 0..nullCounter - 1){
val newElement = (temp[temp.size - 2] difference).format()
temp.add((temp.size - 1), newElement)
}
}
nullCounter = 0
}
element ?: nullCounter
}
return temp
}
測驗:https ://pl.kotl.in/rpbDZ8zkq
uj5u.com熱心網友回復:
沒有辦法決定要替換的數字null。
考慮 iflistOf(1, null, null)或listOf(null, 2, null).
如果您確切知道串列需要是什么,則可以使用IntProgressionorIntRange代替。
// 1, 2, 3, 4, 5, 6, 7
val list1 = IntRange(1, 7).toList()
// 1, 3, 5, 7
val list1 = IntProgression(1, 7, 2).toList()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/477029.html
