Typeerror: list indices must be integers, not tuple

Asked

Viewed 2,952 times

1

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

However, when executed it presents the error: "Typeerror: list indices must be integers, not tuple"

I don’t 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)

Thanks in advance.

  • You at least tried to understand the code of the other question before changing it?

1 answer

1


On the 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 each i inside ap", it does not return you an index but each double within your list.

If you want to do 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 function documentation enumerate python

  • Right, how could I rewrite it to work?

  • Perfect, Leonardo. It worked correctly! Very, Thank you for your patience and help. I will look very calmly at the documentation of the ENUMERATE function. .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.