我试图找出csv文件行元素之间的欧几里得距离。我的csv文件格式如下。
A | B | C | D
1 0 0 2
2 1 1 0
3 0 0 1
首先,用户输入一个输入。例如,如果用户输入1,则输出将为[('1','0')]。然后,从用户处获取第二个输入,求出两点之间的欧氏距离。代码如下。
import csv
from math import*
def euclidean_distance(x,y):
return sqrt(sum(pow(a-b,2) for a, b in zip(x, y)))
with open("file1.csv") as f:
csvr = csv.reader(f)
csvr = list(csvr)
f = open( 'file1.csv', 'rU' ) #open the file in read universal mode
i = int(input("Input1: "))
output = []
for line in csvr[i]:
cells = line.split( ";" )
output.append( ( cells[ 0 ], cells[ 1 ] ) ) #since we want the first and second column
i2 = int(input("Input2: "))
output2 = []
for line in csvr[i2]:
cells = line.split( ";" )
output2.append( ( cells[ 0 ], cells[ 1 ] ) ) #since we want the first and second column
f.close()
print output
print output2
print euclidean_distance(output,output2)
错误如下。我怎样才能修好它?谢谢你的帮助。在
^{pr2}$
下面是如何使用numpy.linalg.norm计算欧几里德距离的示例:
还要注意,输入数据看起来像
^{pr2}$输出是
相关问题 更多 >
编程相关推荐