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

创建带权边列表生成邻接列表时遇TypeError问题求助

问题梳理与解决建议

坐标存储优化

你当前用self.x, self.y = []的方式完全错误,这会让self.x和self.y都变成空列表,根本没法存储多组坐标。正确的做法是把所有坐标统一存到一个列表属性里,比如:

# 初始化时
self.coordinates = []

# 每次添加坐标时(比如拿到x和y值)
self.coordinates.append([x_value, y_value])

这样所有坐标会以[[0,0], [1,0], [2,0], ...]的格式保存,不会出现覆盖问题,所有坐标都会保留。

边列表生成的错误原因

你写的循环逻辑混乱,导致报错:

edge = []
for i in self.x, self.y:
    for j in i[1]:
        edge.append([i[0], j])
        for i in edge:
            print(i)

这里self.x, self.y是两个独立列表,循环时i会依次取self.x里的每个整数元素、self.y里的每个整数元素,所以i是int类型,执行i[1]自然会触发TypeError: 'int' object is not subscriptable。

邻接列表的实现方案

根据路径规划(A*算法)的常见需求,分两种场景给出实现:

场景1:网格中仅上下左右相邻的节点(最常用)

# 先定义上下左右四个移动方向
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
adjacency_list = []

for node in self.coordinates:
    x, y = node
    neighbors = []
    for dx, dy in directions:
        neighbor = [x + dx, y + dy]
        # 检查邻居是否在坐标列表中
        if neighbor in self.coordinates:
            # 计算曼哈顿距离作为权重(网格路径规划常用)
            weight = abs(dx) + abs(dy)
            neighbors.append((neighbor, weight))
    adjacency_list.append(neighbors)

场景2:所有节点两两相连(完全图)

adjacency_list = []

for idx, current_node in enumerate(self.coordinates):
    neighbors = []
    for neighbor_idx, neighbor_node in enumerate(self.coordinates):
        if idx != neighbor_idx:  # 排除节点自身
            # 计算欧几里得距离作为权重
            weight = ((current_node[0] - neighbor_node[0])**2 + (current_node[1] - neighbor_node[1])**2)**0.5
            neighbors.append((neighbor_idx, weight))
    adjacency_list.append(neighbors)

后续A*算法的注意点

  • 邻接列表里的权重会用于计算A*的g值(从起点到当前节点的代价),要根据你的场景选择合适的距离计算方式。
  • 建议给每个坐标分配唯一索引,后续A*中用索引操作会更高效,避免直接比较坐标列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 19:52:27