-4

I have a code that uses functions to calculate the closest edge of a station id based on its geographical coordinates.

The output is a line like this (format xml):

  <edge id="4260662#2" from="1977648762" to="2600872721"/>

I need to extract only the id value from this line which is in this example: 4260662#2, so I tried to use for loop, I put the line in a string named "ch" but when I did "for i in ch:" , it shows me an error: TypeError: iteration over non-sequence.

I tried many solutions but they did not work, can you help me please?enter image description here

Myriam
  • 11
  • 4
  • Please paste the *all* relevant parts of your code as *text*, not as an image. See https://stackoverflow.com/help/mcve. About your code, it seems that, contrary to what you seem to think, closestEdge isn't a string, but probably some object.... – Thierry Lathuille Apr 16 '17 at 10:47

1 Answers1

1

closestEdge is an instance of the sumolib.net.edge.Edge class. It is not a string and can not be treated as such by, for example, iterating over it.

Fortunately the Edge class contains a method, getID(), which can be used to access the id:

distancesAndEdges = sorted([(dist, edge) for edge, dist in edges])
dist, closestEdge = distancesAndEdges[0]

print(closestEdge.getID())

On a related note, you do not need to sort the list of edges to find the closest (that with minimum distance). Instead you can use the min() builtin function with the key argument:

from operator import itemgetter

dist, closestEdge = min(edges, key=itemgetter(1))
print(closestEdge.getID())

Not only is this code more readable, but min() has time complexity O(n), which is faster than O(n log n) for sorted().

mhawke
  • 84,695
  • 9
  • 117
  • 138