且构网

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

Python-将字符串列表转换为浮点数-方括号和小数点导致问题

更新时间:2023-02-21 16:44:30

对于每行,用line[1:-1]修剪第一个和最后一个字符,用.split()分隔空白,并用float()解析每个浮点数.

For each line, trim off the first and last char with line[1:-1], split by whitespace with .split(), and parse each float with float().

line = "[ 0.          0.         -0.24604772  0.        ]"
floats = [float(item) for item in line[1:-1].split()]

print(floats)
>>> [0.0, 0.0, -0.24604772, 0.0]