【问题标题】:python - TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple'python - TypeError:不支持的操作数类型-:'tuple'和'tuple'
【发布时间】:2016-12-28 15:16:51
【问题描述】:

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

一个 |乙| 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)

错误如下。我该如何解决?感谢您的提前。

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

【问题讨论】:

    标签: python csv typeerror euclidean-distance


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2018-04-13
      • 1970-01-01
      • 2020-07-05
      • 2013-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多