You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中如何将Double列表拆分为含循环配对的两个列表?

解决Kotlin中循环配对坐标列表的问题

要实现将形如[x1, y1, x2, y2, x3, y3]的Double列表拆分为循环配对的两个列表,核心是补全zipWithNext()缺失的首尾配对,以下是具体实现方案:

基础实现步骤

  1. 拆分x、y坐标列表:使用filterIndexed按索引奇偶性拆分原列表,得到独立的x坐标列表和y坐标列表。
  2. 生成循环配对:先通过zipWithNext()获取相邻元素的配对,再手动添加最后一个元素与第一个元素的配对,完成循环结构。

完整代码示例

fun main() {
    // 示例输入:x1=1.0, y1=2.0; x2=3.0, y2=4.0; x3=5.0, y3=6.0
    val originalList = listOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0)
    
    // 拆分x、y坐标
    val xList = originalList.filterIndexed { index, _ -> index % 2 == 0 }
    val yList = originalList.filterIndexed { index, _ -> index % 2 == 1 }
    
    // 生成循环配对列表
    val xPairs = xList.zipWithNext() + (xList.last() to xList.first())
    val yPairs = yList.zipWithNext() + (yList.last() to yList.first())
    
    println("x坐标循环配对:$xPairs") // 输出 [(1.0, 3.0), (3.0, 5.0), (5.0, 1.0)]
    println("y坐标循环配对:$yPairs") // 输出 [(2.0, 4.0), (4.0, 6.0), (6.0, 2.0)]
}

复用性优化:扩展函数

如果需要多次使用循环配对逻辑,可以封装成List的扩展函数,同时处理空列表等边界情况:

fun <T> List<T>.circularZipWithNext(): List<Pair<T, T>> {
    return if (isEmpty()) {
        emptyList()
    } else {
        zipWithNext() + (last() to first())
    }
}

// 使用方式
val xPairs = xList.circularZipWithNext()
val yPairs = yList.circularZipWithNext()

原方案问题说明

你最初的代码中,zipWithNext()仅会生成当前元素与下一个元素的配对,当遍历到列表最后一个元素时,没有后续元素可以配对,因此会缺失最后一个元素与第一个元素的循环配对。通过手动追加这一对,即可完成完整的循环结构。

内容的提问来源于stack exchange,提问作者Alexander Glejezer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 13:35:17