簡體   English   中英

python-反向遍歷坐標列表的有效方法是什么

[英]python - what is an efficient way to traverse a list of coordinates in reverse

我有一個當前列表,其中包含來自起點和終點的路徑的點,該點來自3x3矩陣,起始位置為2,2,終止位置為0,0

網格在以下位置還具有不可遍歷的像元:0,1 0,2 1,1

所以網格看起來像這樣:

            -----------------
            |Goal| Wall| Wall |
            ==================
            |    |Wall |      |
            ===================
            |    |     | Start|
            ===================

運行算法以獲得最佳路徑后,我能夠獲得從2,2到0,0的可能方法。

PathCaptured:      ['2,2,1,2,2.0', '2,2,2,1,2.0', '2,1,1,0,5.0', '2,1,2,0,4.0', '1,0,0,0,7.0']

因此,該結構表示為:[startposx,startposy,destx,desty,score]

我希望使用相反的路徑來重建點。

我的問題是我正在創建2個for循環遍歷列表,以確保我將兩點連接起來以得出答案

[[2,2][2,1][1,0][0,0]]

有沒有更簡單的方法可以在python中做到這一點?

用當前代碼更新:

        first_time=True
        for i, e in reversed(list(enumerate(self.action_list))):

            if debug:
                print i, e
            if first_time:
                startx,starty,destx,desty,_ = e.split(",")
                ctr += 1
                box_path[ctr] = [destx, desty]
                ctr += 1
                box_path[ctr] = [startx,starty]
                #box_path.append([destx,desty])
                #box_path.append([startx,starty])
                first_time = False

            else:
                for j in range(len(self.action_list)):
                    dx, dy, dx_1, dy_1,_= self.action_list[j].split(",")
                    Dx,Dy = box_path[ctr]
                    if (Dx == dx_1 and Dy == dy_1):
                        box_path[ctr+1] = [dx,dy]
                        ctr += 1
                        #box_path.append([dx,dy])
                        break
            if debug:
                print box_path

看起來您的返回值在某種意義上被排序,即最終單元格達到某個C1的目標,然后您有一堆從C2到所有相鄰單元格的單元格(一個是C1,其余單元格無關),依此類推。 因此,一旦找到連接到您的單元,便可以向后走,這可以確保您在路徑上(似乎只是在重復進行迭代,這很浪費):

def getStep(stepStr):
    step = map(int,stepStr.split(','))
    return (step[0],step[1]),(step[2],step[3]) #Can return score if you need

goal = (2,2) #Your example

pos = len(self.action_list)-1
start,stop = getStep(self.action_list[pos])
res = [stop]
while start != goal:
    pos -= 1
    nstart,nstop = getStep(self.action_list[pos])
    while nstop != start:
        pos -= 1
        nstart,nstop = getStep(self.action_list[pos])
    res.append(start)
    start = nstart
res.append(goal)

從結束到開始,這將只遍歷列表一次。 內部循環會跳過不連接到下一個單元格的不相關單元格。 我完全忽略了這里的錯誤檢查,例如路徑錯誤(例如, nstop!=start永遠nstop!=start )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM