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

如何将二元障碍坐标元组压缩为三元元组?

问题描述

我是编程新手,现有如下地图:

map = [
    "......",
    "..##..",
    ".##.#.",
    "...###",
    "###.##",
]

其中.代表可行路径,#代表障碍物。我已获取障碍物坐标列表:

list_obstacle = [(3, 2), (4, 2), (2, 3), (3, 3), (5, 3), (4, 4), (5, 4), (6, 4), (1, 5), (2, 5), (3, 5), (5, 5), (6, 5)]

期望输出为:

final_list = [(3, 4, 2), (2, 3, 3), (5, 5, 3), (4, 6, 4), (1, 3, 5), (5, 6, 5)]

请问如何将二元元组列表转换为三元元组列表?以下是我的尝试代码:

final_list = []
for obstacle, line in list_obstacle:
   for each_obstacle in range(obstacle, line)
   final_list.append(obstacle, each_obstacle, line)
print(final_list)
解决方案

需求核心是把**同一行(二元组的第二个元素)中连续的x坐标(二元组的第一个元素)**合并成(起始x, 结束x, 行号)的三元组,可按以下步骤实现:

  1. 按行号对障碍物坐标分组,将同一行的x坐标归集到一起
  2. 对每行的x坐标排序,识别出连续的数值区间
  3. 将每个连续区间转换为目标格式的三元元组

实现代码

from itertools import groupby

list_obstacle = [(3, 2), (4, 2), (2, 3), (3, 3), (5, 3), (4, 4), (5, 4), (6, 4), (1, 5), (2, 5), (3, 5), (5, 5), (6, 5)]

# 先按行号、再按x坐标排序,确保同一行的x是有序的
sorted_coords = sorted(list_obstacle, key=lambda x: (x[1], x[0]))
# 按行号分组
grouped = groupby(sorted_coords, key=lambda x: x[1])

final_list = []
for line, coords in grouped:
    xs = [x for x, _ in coords]
    if not xs:
        continue
    # 初始化第一个区间的起始和结束值
    start_x = xs[0]
    end_x = xs[0]
    # 遍历剩余x坐标,判断是否连续
    for x in xs[1:]:
        if x == end_x + 1:
            end_x = x
        else:
            # 非连续则保存当前区间,重置起始结束值
            final_list.append((start_x, end_x, line))
            start_x = x
            end_x = x
    # 保存最后一个区间
    final_list.append((start_x, end_x, line))

print(final_list)

你的尝试代码问题说明

  • 语法错误:for each_obstacle in range(obstacle, line)语句末尾缺少冒号
  • 方法调用错误:append需要传入单个元组参数,应写成final_list.append((obstacle, each_obstacle, line))
  • 逻辑错误:未按行分组处理连续坐标,仅简单遍历无法实现区间合并的目标

内容的提问来源于stack exchange,提问作者Valentina Peternelj

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 13:55:20