1

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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
D. Waschow
  • 121
  • 2

2 Answers2

3

You can use the map() function:

for p in pnts:
    x, y, z = map(float, p.split(' '))
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
2

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]
Robᵩ
  • 163,533
  • 20
  • 239
  • 308