Omg I killed Kennny
Omg I killed Kennny

Reputation: 321

Python get certain coordinate from list

I have a list of coordinates,like :[(1,2,3),(2,3,4),(3,4,5),(4,5,6)]

I want to get certain number, like x1=1 from (1,2,3), y1=2 from (1,2,3), I don't know if it can be done.

Because I want to calculate the distance between certain two coordinates.

use :

math.sqrt(( x1-x2 )**2 + ( y1-y2 )**2 + (z1-z2 )**2)

Thank you!

Upvotes: 0

Views: 248

Answers (2)

Kasravnd
Kasravnd

Reputation: 107287

I suggest use a dictionary for that aim , you can get it whit list comprehension :

>>> [dict((('x%d'%index,x),('y%d'%index,y),('z%d'%index,z))) for index, (x, y, z) in enumerate(l,1)]
[{'y1': 2, 'x1': 1, 'z1': 3}, {'x2': 2, 'y2': 3, 'z2': 4}, {'x3': 3, 'y3': 4, 'z3': 5}, {'z4': 6, 'y4': 5, 'x4': 4}]

and then instead of math.sqrt(( x1-x2 )**2 + ( y1-y2 )**2 + (z1-z2 )**2) use :

math.sqrt((new_dic['x1']-new_dic['x2'] )**2 + ( new_dic['y1']-new_dic['y2'] )**2 + (new_dic['z1']-new_dic['z1'] )**2)

Upvotes: 1

Kevin
Kevin

Reputation: 76194

You can use indexing to access items in a sequence. It is possible to use multiple indices to drill into a multidimensional array.

>>> seq = [(1,2,3),(2,3,4),(3,4,5),(4,5,6)]
>>> seq[0][0]
1
>>> seq[0][1]
2

Here, seq[0][0] accesses the first item in the first coordinate, and seq[0][1] accesses the second item in the first coordinate.

Upvotes: 1

Related Questions