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():

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.

你可能感兴趣的:(python)