从列表中删除列表

时间:2014-04-03 09:56:48

标签: python-2.7

我有一个坐标列表和一个可以解决它们之间距离的函数。

我正在尝试创建一个以起点和坐标列表作为输入的函数。然后函数找到最接近起点的点,然后找到最接近该点的点...

我遇到的问题是下一个可能是最接近的坐标,所以在这一点上重复,所以我需要删除它。

def getroute(start, allpoints):
    routelist = [start]
    next = getclosestpoint(start, allpoints)
    allpoints.remove(start)
    for i in range(0,len(allpoints)):
        routelist.append(next)
        *allpoints.remove(next[1])*
        next = getclosestpoint(next[1], allpoints)
    return routelist

我一直收到错误:

allpoints.remove(next[1])
TypeError: 'int' object has no attribute '__getitem__'

但是当我打印下一个[1]时,我得到例如[4,1],这是在我的所有点列表中:[ - 3,-3],[1,-1],[4,1],[ - 2,5]

任何人都可以解释为什么不删除它?

感谢。

更新: 我想我已经通过以下方式进行了管理:

latlngs = [[-3, -3], [1,-1], [4,1], [-2,5], [2,2], [-6,1]]

def gethypot(latlng):
    hypot = sqrt(pow(latlng[0],2)+pow(latlng[1],2))
    return hypot

def getdistance(point1, point2):
    lat_apart = point2[0] - point1[0]
    lng_apart = point2[1] - point1[1]
    distance = gethypot([lat_apart,lng_apart])
    return distance

def getclosestpoint(start, points):
    allpoints = points
    distances = []
    allpoints.remove(start)
    shortest = 0
    for i in range(0,len(allpoints)):
        distances.append(getdistance(start,allpoints[i]))       
        if getdistance(start,allpoints[i]) == min(distances):
            shortest = allpoints[i]
    return shortest

def getroute(start, allpoints):
    routelist = [start]
    points = allpoints
    next = getclosestpoint(start, points)
    for i in range(0,len(points)):
        routelist.append(next)
        next = getclosestpoint(next, points)
    return routelist

1 个答案:

答案 0 :(得分:0)

我认为你的循环是错误的。实际上,您希望将所有点从allpoints移至routelist,以便您可以使用:

def getroute(start, allpoints):
    routelist = []
    next = start
    while allpoints:
        routelist.append(next)
        allpoints.remove(next)
        _, next = getclosestpoint(next, allpoints)
    return routelist
相关问题