且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将字符串列表转换为float

更新时间:2023-11-04 16:54:04

使用列表理解:

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.