Python 中不支持的操作数类型

Unsupported Opreand Type in Python

Hello this is error message that i recieved, please help me to find where could be the problem.

<ipython-input-52-2e0822fefabf> in main()
     11         k = 3
     12         for x in range(len(testSet)):
---> 13                 neighbors = getNeighbors(trainingSet, testSet[x], k)
     14                 result = getResponse(neighbors)
     15                 predictions.append(result)

<ipython-input-48-401931b7da2b> in getNeighbors(trainingSet, testInstance, k)
      4         length = len(testInstance)-1
      5         for x in range(len(trainingSet)):
----> 6                 dist = euclideanDistance(testInstance, trainingSet[x], length)
      7                 distances.append((trainingSet[x], dist))
      8         distances.sort(key=operator.itemgetter(1))

<ipython-input-45-f927a4da7f1b> in euclideanDistance(instance1, instance2, length)
      3         distance = 0
      4         for x in range(length):
----> 5                 distance += pow((instance1[x] - instance2[x]), 2)
      6         return math.sqrt(distance)

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

这些值:testInstance, trainingSet[x]

不是 intfloat。它们应该是,因为您不能从字符串中减去字符串。

你可以这样做:

neighbors = getNeighbors(int(trainingSet), int(testSet[x]), k)

如果它们是浮点数,则这样:

neighbors = getNeighbors(float(trainingSet), float(testSet[x]), k)