TypeError: list indices must be integers, not tuple

1

I have a code that calculates the Euclidean distance between two points.

However, when I execute it it presents the error: "TypeError: list indices must be integers, not tuple"

I do not know what I'm doing wrong.

Below the code:

import math

AP_X = [1,2]
AP_Y = [1,2]
demanda_X = [1,2]
demanda_Y = [1,2]

ap = list(zip(AP_X, AP_Y))
demanda = list(zip(demanda_X, demanda_Y))

distancia = []

for i in ap:
  for j in demanda:
    distancia.append((math.sqrt(pow(demanda_X[j] - AP_X[i], 2) + pow(demanda_Y[j] - AP_Y[i], 2))))

print (distancia)

Thank you in advance.

    
asked by anonymous 07.03.2017 / 01:38

1 answer

1

On line ...

distancia.append((math.sqrt(pow(demanda_X[j] - AP_X[i], 2) + pow(demanda_Y[j] - AP_Y[i], 2))))

... you take your variable j and i as indexes. However, in your loop, i and j are tuples. When you iterate "for every i within ap ", it does not return you an index, but every double within your list.

If you want to do it through indexes, try something like:

for ida, tupla_a in enumerate(ap):
    for idj, tupla_b in enumerate(demanda):
      distancia.append((math.sqrt(pow(demanda_X[idj] - AP_X[ida], 2) + pow(demanda_Y[idj] - AP_Y[ida], 2))))

See the documentation for the enumerate of Python

    
07.03.2017 / 01:46