如何将字符串列表转换为浮点数数组?

How can I convert a list of strings to an array of float numbers?

我正在尝试将字符串列表转换为 Python 中的可调用浮点数数组,但我遇到了错误。这是我的代码的一部分:

list=['1 2 3', '4 5 6']
for x in list:
   x=float(x)

ValueError: could not convert string to float: '1 2 3'

您可以为此使用嵌套列表理解。第一个可以遍历您的字符串,然后对于每个字符串,您可以 str.split 并将每个元素从那里转换为 float

>>> data = ['1 2 3', '4 5 6']
>>> [[float(i) for i in row.split()] for row in data]
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]