這將返回一個包含輸入爲元組(X,Y)每兩個連續點之間的(歐幾里得)距離的列表。這些代碼片段假設Python 3.x,如果您使用Python 2.7,則可能需要進行小的更改。您的標籤不清楚這一點。
import math
def distances(lst):
ln = len(lst)
dists = []
if ln >= 2: # if array contains no or only 1 tuple, return []
for index, tup in enumerate(lst[:ln - 1]):
x1, y1 = tup
x2, y2 = lst[index + 1] # gets x and y of next tuple in the array
dists.append(math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2))
return dists
array0 = []
array1 = [(2, 4), (-4, 2)]
array2 = [(5, 2), (-1, 3), (6, -6)]
array3 = [(2, 4), (-4, 2), (10, -5), (9, -2)]
print(distances(array0))
print(distances(array1))
print(distances(array2))
print(distances(array3))
輸出:
[]
[6.324555320336759]
[6.082762530298219, 11.40175425099138]
[6.324555320336759, 15.652475842498529, 3.1622776601683795]
如果你要打印的距離,你提到的方式:
import math
def distances(lst):
ln = len(lst)
if ln >= 2:
for index, tup in enumerate(lst[:ln - 1]):
x1, y1 = tup
x2, y2 = lst[index + 1]
dist = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
print(lst[index:index + 2], "=", dist)
array = [(5, 2), (-1, 3), (6, -6)]
distances(array)
輸出:
[(5, 2), (-1, 3)] = 6.082762530298219
[(-1, 3), (6, -6)] = 11.40175425099138
相同的功能之前可以使用numpy模塊instea來實現數學的d:
import numpy as np
def distances(lst):
ln = len(lst)
dists = []
if ln >= 2:
for index, tup in enumerate(lst[:ln - 1]):
dists.append(np.linalg.norm(lst[index + 1] - tup))
return dists
array0 = np.array([])
array1 = np.array([(2, 4), (-4, 2)])
array2 = np.array([(5, 2), (-1, 3), (6, -6)])
array3 = np.array([(2, 4), (-4, 2), (10, -5), (9, -2)])
print(distances(array0))
print(distances(array1))
print(distances(array2))
print(distances(array3))
輸出:
[]
[6.324555320336759]
[6.0827625302982193, 11.401754250991379]
[6.324555320336759, 15.652475842498529, 3.1622776601683795]
如果你只想要包含在列表中有兩個元組之間的距離:
import math
def distance(lst):
return math.sqrt((lst[1][0] - lst[0][0]) ** 2 + (lst[1][1] - lst[
0][1]) ** 2)
array = [(2, 4), (-4, 2)]
print(distance(array))
輸出:
6.324555320336759
你到底要什麼?你想傳遞一個元組對的列表並獲得它們之間的距離嗎?這將如何工作?或者只是傳入2對? – ospahiu
你需要做一些元組拆包 - 例如對於Python <3.5,'Distance(* array [0],* array [1])',for> = 3.5 – asongtoruin
例如,如果我的輸入是array = [[array] [array] (5,2),( - 1,3),(6,-6)],我想得到輸出[(5,2),(-1,3)] = 6.082,[(-1,3) ,(6,-6)] = 11.401 – Daniel