Home > Mobile >  subtracting every element of a list from a previous element in a dictionary
subtracting every element of a list from a previous element in a dictionary

Time:10-20

I have a dictionary which has a 2D list (list of a list). This 2D list contains x and y coordinates [x,y] of a particle. Whenever the particle moves, its new coordinates are appended to this 2D list in a dictionary. I want to calculate the distance between every location and append the result to another list (can just be a normal list without dictionary). What I want is something like the following:

dist1 = sqrt((x1-x0)^2   (y1-y0)^2)
dist2 = sqrt((x2-x1)^2   (y2-y1)^2)
.....
distN = sqrt((xN-xN-1)^2   (yN-yN-1)^2)

but I am having issues in accessing elements of a list in a dictionary. I have a very long 2D list but you can use the below example to give me some suggestions.

c = {"coordinates":[[1,2],[3,4],[5,6],[7,8]]}
for k, dk in c.items():
    for x in dk:
        print(x[0], x[1])

I can access one element in the dk at a time in a loop but how to get the previous one? There should be a nice way of doing it but I just don't know.

Any help will be appreciated.

CodePudding user response:

Using a for loop (probably not the most efficient solution):

import numpy as np

c = {"coordinates":[[1,2],[3,4],[5,6],[7,8]]}
coordinates = np.array(c['coordinates'])

distances = []
for i in range(1, len(coordinates)):
    distances.append(np.linalg.norm(coordinates[i-1] - coordinates[i]))
print(distances)
# [2.8284271247461903, 2.8284271247461903, 2.8284271247461903]

I also used numpy and its linalg.norm function to calculate the distance (How can the Euclidean distance be calculated with NumPy?), but you could ofcourse use your own function or calculation in case you'd want that.

CodePudding user response:

I tried this and it also works:

c = {"coordinates":[[1,2],[3,4],[15,6],[7,8]]}
l1 = []
for k, dk in c.items():
    for x in dk:
        l1.append(x)
print(l1)
dist = [math.sqrt((p1[0]-p0[0])**2   (p1[1]-p0[1])**2) for p1,p0 in zip(l1,l1[1:]

as others suggested in this question, better way to get l1 is to use the following command:

l1 = c["coordinates"]
dist = [math.sqrt((p1[0]-p0[0])**2   (p1[1]-p0[1])**2) for p1,p0 in zip(l1,l1[1:]
  • Related