python - TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple'

python - TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple'

我试图找到 csv 文件行元素之间的欧氏距离。我的 csv 文件格式如下。

一个 |乙 |丙 |丁

1 0 0 2

2 1 1 0

3 0 0 1

首先,用户输入。例如,如果用户输入 1,则输出将为 [('1', '0')]。然后,从用户那里获取第二个输入以找到两点之间的欧几里得距离。代码如下。


import csv
from math import*</p>

<pre><code>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)

报错如下。我该如何解决?感谢您的预付款。

 return sqrt(sum(pow(a-b,2) for a, b in zip(x, y)))
 TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple'

下面是如何使用numpy.linalg.norm计算欧氏距离的例子:

import numpy as np

csv = np.genfromtxt ('file1.csv', delimiter=",")

i = int(input("Input1: "))
second = csv[i,0:2]    #selects ith row and 0th & 1st columns 
i2 = int(input("Input2: "))
third = csv[i2,0:2] #selects ith row and 0th & 1st columns 

print second
print third

a=np.array(second)
b=np.array(third)
dist = np.linalg.norm(a-b)
print dist

还要注意输入数据看起来像

A B C D
1 0 0 2
2 1 1 0
3 0 0 1

输出是

Input1: 1
Input2: 2
[ 1.  0.]
[ 2.  1.]
1.41421356237