我无法在for循环的列表中增加特定值

时间:2019-03-08 12:44:33

标签: python list for-loop

我将python用于自动驾驶汽车项目。因此,我研究了一种从Dijkstra算法返回值的算法。我给出算法(位置,目的地),它返回最短路径。然后,我要添加路线值。但是我无法在某个时候增加这些值。这是我的代码:

coordinates = [['X',0,20],['B',15,20],['H',15,45],['G',20,45],['Y',20,55]]
dir = dijsktra(graph,'X','Y')
indexes = []
for i in range(len(dir)):
   for j in range(len(coordinates)):
           if dir[i] == coordinates[j][0]:
               indexes.append(j)

for i in range(len(dir)-1):
    if coordinates[indexes[i]][1] == coordinates[indexes[i+1]][1]:
        turnons.append(['R',i+1])
    elif coordinates[indexes[i]][2] == coordinates[indexes[i+1]][2]:
        turnons.append(['L',i+1])

list_lenght = len(dir) + len(turnons)
for i in range(list_lenght):
    for j in range(len(turnons)):
        if turnons[j][1] == i:
            dir.insert(i,turnons[j][0])
            if turnons[j] != turnons[len(turnons)-1]:
                print(turnons[j])
                turnons[j + 1][1] += 1 // That's is the problem.

这是预期的输出:['L', 1]['R', 3]['L', 5]['R', 7]

这就是我得到的:['L', 1]['R', 3]['L', 4]

这里

  • L =左
  • R =正确

1 个答案:

答案 0 :(得分:0)

女士们,先生们,我们找到了他。

coordinates = [['X',0,20],['B',15,20],['G',20,45],['Y',20,55],['H',15,45]]
dir = dijsktra(graph,'B','X')
indexes = []
for i in range(len(dir)):
    for j in range(len(coordinates)):
            if dir[i] == coordinates[j][0]:
                indexes.append(j)

turnons = []
newdir = []
for i in range(len(dir)-1):
    if coordinates[indexes[i]][1] == coordinates[indexes[i+1]][1]:
        turnons.append(['R',i+1])
    elif coordinates[indexes[i]][2] == coordinates[indexes[i+1]][2]:
        turnons.append(['L',i+1])

uzunluk = len(dir) + len(turnons)
turnsyc = 0
dirsyc = 0
print(dir,turnons)
for i in range(uzunluk):
    if i % 2 == 0 or i == 0:
        newdir.append(dir[dirsyc])
        dirsyc += 1
    else:
        newdir.append(turnons[turnsyc][0])
        turnsyc += 1