簡體   English   中英

我有一個列表,我想計算列表中每個項目與列表中所有其他項目的平均距離

[英]I have a list and I want to calculate the average distance of each item in the list to all the other items in the list

該列表包含 x,y 坐標,如下所示, [[1,2], [2,3], [5,6]....]我知道如何計算兩個坐標之間的距離。 我需要計算 [1,2] 與列表中所有其他坐標之間的距離,然后移動到 [2,3] 並執行相同的操作,依此類推。

解決這個問題的最佳方法是什么?

我最初的方法是創建兩個 for 循環:

for i in range (0, len(coordinateslist)):
    for j in range (0, len(coordinateslist)):
        distanceList.append(computeDist(coordinateslist[i),coordinateslist[j])

您需要定義要比較的坐標對。 有關存在哪些可能的比較,請參見下表。

*   A  B  C  ...

A   AA AB AC
B   BA BB BC
C   CA CB CC
...          ...

假設有效的比較是 (AB, AC, BC) 或 (BA, CA, CB) 但不是兩者。

你需要稍微改變你的循環。

from itertools import islice

for i, point in enumerate(coordinateslist):
    for other in islice(coordinateslist, i):
        distanceList.append(computeDist(point, other))

所以一個蠻力解決方案可能看起來像... ex[x,y,z,l,m...] 計算每對距離只計算一次 x:(points -x) y:(points -x -y) z: (點-x -y -z)等...

def calculate_distances(points)
    tocalc = points
    answers = dict()
    for point in points:
        for dot in tocalc:
            if point!=dot: # distance to itself is always 0
                answers[sorted([point,dot])] = distance(point,dot)
        tocalc.pop(0) #no need to process this item again
     return answers

然后您可以執行sum(answers.values()) 、 'sorted(answers,key=lambda k: k.value)` 等操作。

從上面可以清楚地看出,我們實際上不需要第二個列表來管理要計算的內容,我們只需要兩個索引,所以讓我們嘗試用最小的 memory 足跡來做:

def calculate_distances(points):
    currind=0
    tocalc_ind = 1
    # we also know the answer looks like a matrix with diagonal of zeros...
    answers = dict()
    for p_ind in range(len(points)):
        currind = p_ind
        if points[currind] not in answers:
            answers[points[currind]] = dict()
        for c_ind in range(tocalc_ind,len(points)): # implicitly skipping previous
            answers[points[currind]][points[c_ind]] = distance(points[currind],points[c_ind])
    return answers

請注意,我更改了數據格式以幫助可視化答案。 我確信還有其他優化,但這應該在 O(n) 時間內運行,因為通常 O(n*n) 的第二個嵌套循環每回合都會減少。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM