简体   繁体   English

访问2d python列表中的行以计算值之间的距离

[英]Accessing rows in a 2d python list for calculating distance between values

I have a list with a few hundred values which looks like this: 我有一个包含数百个值的列表,看起来像这样:

(0.0021265099091875685, 0.0017700721644805513) (0.0026319917728469086, 0.002632415013842871)

I want to calculate the euclidean distance between each row. 我想计算每行之间的欧几里得距离。

The way I plan on calculating it is something like this: 我计划的计算方式是这样的:

sqrt(0.0021265099091875685 - 0.0026319917728469086)^2 + (0.0017700721644805513 -  0.002632415013842871)^2

I'm having trouble working out how I can access each value in order to do those calculations. 我在设计如何访问每个值以进行这些计算时遇到了麻烦。 If anyone has any ideas about doing this it would be very helpful. 如果有人对此有任何想法,那将非常有帮助。 Thanks 谢谢

EDIT: I'm pulling data from a MySQL db. 编辑:我正在从MySQL数据库中提取数据。 Initially I had two lists, when printed out, a list would look like this: 最初我有两个列表,当打印出来时,列表看起来像这样:

0.00212650990919 0.00263199177285 0.00332920813651 0.00268428300012 0.00245768768193

I then created a new list by doing this: 然后,我通过执行以下操作创建了一个新列表:

someList = zip(list1 , list2)

which gave me the output I have above. 这给了我上面的输出。

You can use zip: 您可以使用zip:

l1=(0.0021265099091875685, 0.0017700721644805513)
l2=(0.0026319917728469086, 0.002632415013842871)
result=[(x-y)**(1/2) for x,y in zip(l1,l2)]

I am not sure how your data is going to be from your question. 我不确定从您的问题中得到的数据如何。 I am assuming your data to be as: 我假设您的数据为:

data = [
[(0.0021265099091875685, 0.0017700721644805513), (0.0026319917728469086, 0.002632415013842871)],
[(0.0021265099091875685, 0.0017700721644805513), (0.0026319917728469086, 0.002632415013842871)],
[(point-one), (point-two)],
...
]

This will then give you what you need: 这将为您提供所需的内容:

[pow(sqrt(item[1][0] - item[0][0]), 2) + pow((item[1][1] -  item[0][1]), 2) for item in data]

Assuming your list looks like this: 假设您的列表如下所示:

lst = [ ((x1,y1),(x2,y2)), ... ]

Then you can just do: 然后,您可以执行以下操作:

import math
distances = [ math.sqrt((p1[0]-p2[0])**2.0 + (p1[1]-p2[1])**2.0) for p1, p2 in lst ]

Let's say your list looks something like this... 假设您的清单看起来像这样...

xyz = [(0.0021265099091875685, 0.0017700721644805513), (0.0026319917728469086, 0.002632415013842871), ...]

You can also do... 你也可以...

For item in xyz:
    first_num = item[0]
    second_num = item[1]

Assuming your data looks something like this: 假设您的数据如下所示:

points = [
    (a, b),
    (c, d),
    (e, f),
    ...
]

Then you might do something like this: 然后,您可以执行以下操作:

d = lambda x, y: ((y[0] - x[0]) ** 2 + (y[1] - x[1]) ** 2) ** 0.5
distances = [d(*pair) for pair in zip(points, points[1:])]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM