Turning A List Of Strings Into Float
I printed some data from an external file and split the data into a string: string = data splitstring = string.split(',') print(splitstring) which gave me: ['500', '500', '0.5', '
Solution 1:
Use a list comprehension:
splitstring = [float(s) for s in splitstring]
or, on Python 2, for speed, use map()
:
splitstring = map(float, splitstring)
When you loop over a list in Python, you don't get indexes, you get the values themselves, so c
is not an integer but a string value ('500'
in the first iteration).
You'd have to use enumerate()
to generate indices for you, together with the actual values:
for i, value in enumerate(splitstring):
splitstring[i] = float(value)
or use for c in range(len(splitstring)):
to only produce indices. But the list comprehension and map()
options are better anyway.
Post a Comment for "Turning A List Of Strings Into Float"