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?
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()
.