python 将list中的string转化为float_将字符串列表转换为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', '50', '1.0', '0.75', '0.50', '0.25', '0.00']

I tried to turn them into floats using this method:

for c in splitstring:

splitstring[c]=float(splitstring[c])

But it gives me this error:

Traceback (most recent call last):

File "/Users/katiemoore/Documents/MooreKatie_assign10_attempt2.py", line 44, in

splitstring[c]=float(splitstring[c])

TypeError: list indices must be integers, not str

解决方案

Use a list comprehension:

splitstring = [float(s) for s in splitstring]

or, on Python 2, for speed, use map

你可能感兴趣的:(python)