python - TypeError:不支持的操作数类型 - :' tuple'和'元组'

时间:2016-12-28 15:16:51

标签: python csv typeerror euclidean-distance

我尝试在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)

错误如下。我该如何解决?谢谢你的进步。

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)

1 个答案:

答案 0 :(得分:1)

以下是如何使用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