KOTLIN · 컬렉션
zipWithNext와 scan
zipWithNext로 연속 원소를 쌍으로 묶고, scan으로 누적 결과를 추적합니다.
컬렉션고급zipWithNextscanrunningFoldtime-series
핵심 설명
zipWithNext로 연속 원소를 쌍으로 묶고, scan으로 누적 결과를 추적합니다.
Kotlin code
fun main() {
val temps = listOf(20, 22, 19, 25, 23, 28, 30, 27)
// zipWithNext: 연속 쌍
val changes = temps.zipWithNext { a, b -> b - a }
println("온도 변화: $changes")
// 연속 상승 감지
val rising = temps.zipWithNext().filter { (a, b) -> b > a }
println("상승 구간: $rising")
// scan (runningFold): 누적 결과
val cumSum = temps.scan(0) { acc, t -> acc + t }
println("누적합: $cumSum")
// 이동 평균 (windowed + average)
val movingAvg = temps.windowed(3) { it.average() }
println("이동평균: ${movingAvg.map { "%.1f".format(it) }}")
// 연속 동일값 그룹
val data = listOf(1, 1, 2, 2, 2, 3, 1, 1)
val groups = buildList {
var current = mutableListOf(data[0])
for (i in 1 until data.size) {
if (data[i] == data[i - 1]) current.add(data[i])
else { add(current.toList()); current = mutableListOf(data[i]) }
}
add(current.toList())
}
println("런 그룹: $groups")
}학습 팁
zipWithNext는 시계열 데이터의 변화량, 차분, 추세 감지에 매우 유용합니다.
주의할 점
scan의 결과 리스트는 원본보다 하나 더 길어집니다(초기값 포함). 인덱스 매핑 시 주의하세요.
자주 묻는 질문
zipWithNext와 scan란 무엇인가요?
zipWithNext 로 연속 원소를 쌍으로 묶고, scan 으로 누적 결과를 추적합니다.
zipWithNext와 scan 학습 시 주의할 점은 무엇인가요?
scan 의 결과 리스트는 원본보다 하나 더 길어집니다(초기값 포함). 인덱스 매핑 시 주의하세요.
Continue Learning
Kotlin 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.