gpt4 book ai didi

python - 函数给出错误 ValueError : list. remove(x): x not in list

转载 作者:行者123 更新时间:2023-12-03 19:13:29 29 4
gpt4 key购买 nike

我正在制作一个程序来寻找最近的房子和房子列表的过程。这 3 个函数用于查找类(class),当我去打印结果时,最后给出了错误:

File "C:/Users/ASUS/.spyder-py3/tp_1.py", line 88, in percurso
Casas.remove(pos_i)

ValueError: list.remove(x): x not in list
def distancia_casas(P1, P2):
"returns distance between points"
delta_x = P2[0] - P1[0]
delta_y = P2[1] - P1[1]
distance = ((delta_x ** 2) + (delta_y ** 2)) ** 0.5
return distance
def casa_mais_proxima(P, Casas):

pos_inicial = Casas[0]
pos_mini = (len(Casas), len(Casas))
dist_mini = distancia_casas(P, pos_mini)

for c in Casas:
dist = distancia_casas(P, c)

if dist < dist_mini:
pos_mini = c
dist_mini = dist

elif dist == dist_mini and pos_inicial[0] > c[0]:
pos_mini = pos_inicial

elif dist == dist_mini and pos_inicial[0] < c[0]:
pos_mini = c

elif dist == dist_mini and pos_inicial[0] == c[0] and pos_inicial[1] > c[1]:
pos_mini = pos_inicial

elif dist == dist_mini and pos_inicial[0] == c[0] and pos_inicial[1] < c[1]:
pos_mini = c

elif dist > dist_mini:
pos_mini = pos_mini

else:
pos_mini = c

return pos_mini
def percurso(Inicial, Casas):

pos_i = Inicial

course = [pos_i,]

n = len(Casas) - 1

for c in range(n):
print(pos_i, Casas)

pos_i = casa_mais_proxima(pos_i, Casas)

Casas.remove(pos_i)

course.append(pos_i)

if (len(Casas) - 1) != 0:

course.append(Casas[0])

return course

print("percurso", percurso((3,2),[(0,1),(1,0),(1,2),(2,3)]))

谁能帮帮我?我已经为此苦苦挣扎了 3 天,却一无所获

最佳答案

您不应该在遍历列表时从列表中删除项目。如错误消息所述,您正在尝试删除不存在的元素。因此:

  1. 您可以使用列表理解来创建一个仅包含您要删除的元素的新列表:

    no_casas = []
    for c in range(n):
    print(pos_i, Casas)

    pos_i = casa_mais_proxima(pos_i, Casas)

    no_casas.append(pos_i)

    course.append(pos_i)

    for item in no_casas:
    Casas.remove(item)

但是,这种方法也会导致相同的异常,因为 casa_mais_proxima 可以多次返回 Casa 中的相同元素(这是该函数的预期行为吗? )

因此:

  1. 您可以使用Try/Except ValueError:

    try:
    Casas.remove(pos_i)
    course.append(pos_i)


    except ValueError:
    print(str(pos_i) + " not in Casas")

输出:

(3, 2) [(0, 1), (1, 0), (1, 2), (2, 3)]
(2, 3) [(0, 1), (1, 0), (1, 2)]
(3, 3) not in Casas
(3, 3) [(0, 1), (1, 0), (1, 2)]
(3, 3) not in Casas
percurso [(3, 2), (2, 3), (2, 3), (3, 3), (3, 3), (0, 1)]

关于python - 函数给出错误 ValueError : list. remove(x): x not in list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61411914/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com