Home > database >  How do I refer to an element in a nested list within a for-loop?
How do I refer to an element in a nested list within a for-loop?

Time:12-27

I have a nested list of coordinates [[x1, y1],[x2, y2],[x3,y3]...].

I want to use a for-loop in order to determine the distance in the x-direction between two consecutive points. I want to do the same thing for the y-direction later. This is my attempt so far:

p1=[X1, Y1]
p2=[X2, Y2]
p3=[X3, Y3]
p4=[X4, Y4]
p5=[X5, Y5]
coordiantes = [p1, p2, p3, p4, p5]
    
for i in coordinates:
            p1_x = i[0]
            p2_x = i[0] 1
            p1_y = i[1]
            p2_y = i[1] 1
            distance_x = p2_x - p1_x

Apparently, i[0] 1 doesn't give you the subsequent x-value in the next list but adds 1 to the first x-value.

My question is how do I refer to the subsequent x-value in my nested list? So, if i referred to p1, I also want to get p2 in that loop.

I also tried adding another variable j and assigning it j = i 1 so that I can refer to the subsequent x-value by using j[0]. However, I get the error that one cannot concatenate list to int.

Thank you in advance!

CodePudding user response:

for i in coordinates is a for-each loop. You don't have access to the current index, i is directly the list child.

You should loop using range or enumerate if you want to access the adjacent item by incrementing current index. For example,

for ind in range(len(coordinates)-1):
            p1_x = coordinates[ind][0]
            p2_x = coordinates[ind 1][0]
            p1_y = coordinates[ind][1]
            p2_y = coordinates[ind 1][1]
            distance_x = p2_x - p1_x

The range limit is len-1 because we don't want to process the last element (ind 1 would be out of bounds).

CodePudding user response:

for i, n in enumerate(coord):
    try:
        print(coord[i]
        print(coord[i 1])
    except IndexError:
        pass

try/except part for indexerror. except that, gives an error in last digit. or also you could use :

for i, n in enumerate(coord):
    if i == len(coord)-1:
        pass
    else:
        print(coord[i])
        print(coord[i 1])

also, for enumerate basically you could use range(len(coord)) and without try/except and if part range(len(coord)-1) gives what you want to

  • Related