将字符串列表转换为float [英] 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)
这给了我
['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 <module>
splitstring[c]=float(splitstring[c])
TypeError: list indices must be integers, not str
推荐答案
使用列表理解:
splitstring = [float(s) for s in splitstring]
,或者在Python 2上,为了提高速度,请使用map()
:
or, on Python 2, for speed, use map()
:
splitstring = map(float, splitstring)
当您在Python中循环访问列表时,没有得到索引,而是得到了值,因此c
不是整数,而是字符串值(第一次迭代.)
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).
您必须使用enumerate()
为您生成索引以及实际值:
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)
或使用for c in range(len(splitstring)):
仅 生成索引.但是无论如何,列表理解和map()
选项还是更好.
or use for c in range(len(splitstring)):
to only produce indices. But the list comprehension and map()
options are better anyway.
这篇关于将字符串列表转换为float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!