Search code examples
pythonxmldelimited

Breaking an XML string into three floats


I'm parsing XML data that contains string values, space delimited, that represent floating point values:

<Pnts>
  <P> 123.456 987.654 867.5309</P>
  <P> 345.766 234.132 654.4564</P>
  ...

For each of the P items I need to assign the three float values to three variables. Currently I'm doing this:

for p in pnts:
    x, y, z = p.split(' ')

    x = float(x)
    y = float(y)
    z = float(z)

Is there a more direct (elegant) way to assign the three float variables without first setting them to strings and then re-defining them?


Solution

  • You can use a list comprehension or generator expression:

    x,y,z = [float(f) for f in p.split()]
    

    or

    x,y,z = (float(f) for f in p.split())
    

    Or you could convert all of the data in fell swoop:

    data = [[float(f) for f in p.split()] for p in pnts]