iterate through a list of tuples with for loop

Viewed 83

i have a list consists of point tuples with first points from 1st traj (traj[0]) and second points from 2nd traj (traj[1]) . I want to go through every tuple and compare their first points and if they are equal (e.g, 41 or 47 in list below), then check for some condition( calculate the distance between points in every tuple separately and return the point from 2nd traj with min distance as the correspond point to 1st point). what is the cleanest way to do this? this is my list:

[(40, 10),
 (41, 11),
 (41, 12),
 (42, 13),
 (43, 14),
 (44, 15),
 (45, 16),
 (46, 17),
 (47, 18),
 (47, 19),
 (47, 20),
 (48, 21),
 (49, 22)]

i tried:

c=[]
for j in range(len(list)):
             if (j+1)==(len(list)-1):
                if list[j][0]==list[j+1][0]:
                    d=distance(traj[0][j][0],traj[1][j][1])
                    d1=distance(traj[0][j+1][0],traj[1][j+1][1])
                    if (d < d1):    
                            c.append(traj[1][list[j][1]])
                            break
                    elif (d > d1) :
                            c.append(traj[1][list[j+1][1]])  
                            break
                else:
                    c.append(traj[1][list[j][1]])
                    c.append(traj[1][list[j+1][1]])
                    
                    break              
             elif list[j][0]==list[j+1][0]: 
                        d=distance(traj[0][j][0],traj[1][j][1])
                        d1=distance(traj[0][j+1][0],traj[1][j+1][1])
                        if (d < d1): 
                                     c.append(traj[1][list[j][1]])

                        elif (d > d1):
                                     c.append(traj[1][list[j+1][1]])
                                
             elif list[j][0]==list[j-1][0]:  
                continue           
          
             else:
                 c.append(traj[1][list[j][1]]) 

i know one problem with my code is that it doesn't work for more than 2 corresponds and i was wondering if there would be a much more clean way for checking for the last point in the list and also don't get duplicate points.

my output should looks like this:

 c=[10, (11 or 12), 13, 14, 15, 16, 17, (18 or 19 or 20), 21, 22]

although instead of point number, their coordinates from 2nd traj should be in the above list.

0 Answers
Related