【问题标题】:Calculate Euclidean Distance between all the elements in a list of lists python计算列表python列表中所有元素之间的欧几里得距离
【发布时间】:2020-05-13 10:13:03
【问题描述】:

我有一个列表列表。我想找到所有对与自身之间的欧几里德距离并创建一个 2D numpy 数组。自身之间的距离将在该位置为 0,当对不同时该值。 列表列表示例:[[0, 42908],[1, 3],[1, 69],[1, 11],[0, 1379963888],[0, 1309937401],[0, 1],[0, 3],[0, 3],[0, 77]] 我想要的结果是

  0 1 2 3 4 5 6 7 8
0 0 x x x x x x x x
1   0 x x x x x x x
2     0 x x x x x x 
3       0 x x x x x
4 .................
5 .................
6 .................
7 .................
8 .................

x 表示差异值。句点表示结果应遵循矩阵中所示的结果。我需要有关 python 代码的帮助。行和列中 0、1、2 等的数量定义了内部列表索引。

【问题讨论】:

标签: python euclidean-distance


【解决方案1】:

你可以直接使用numpy来计算距离:

pts = [[0, 42908],[1, 3],[1, 69],[1, 11],[0, 1379963888],[0, 1309937401],[0, 1],[0, 3],[0, 3],[0, 77]]
x = np.array([pt[0] for pt in pts])
y = np.array([pt[1] for pt in pts])
np.sqrt(np.square(x - x.reshape(-1,1)) + np.square(y - y.reshape(-1,1)))

【讨论】:

    【解决方案2】:

    有宝马的绝妙答案。 使用列表推导的另一种可能的解决方案如下:

    import numpy as np
    a=[[0, 42908],[1, 3],[1, 69],[1, 11],[0, 1379963888],[0, 1309937401],[0, 1],[0, 3],[0, 3],[0, 77]]
    # generate all the distances with a list comprehension
    b=np.array([  ((a[i][0]-a[j][0])**2 + (a[i][1]-a[j][1])**2)**0.5 for i in range(len(a)) for j in range(i,len(a))])
    
    n = len(b)
    # generate the indexes of a upper triangular matrix
    idx = np.triu_indices(n)
    # initialize a matrix of n*n with zeros
    matrix = np.zeros((n,n)).astype(int)
    # assign to such matrix the results of b
    matrix[idx] = b
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-24
      • 1970-01-01
      • 1970-01-01
      • 2017-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多