提问人:FNM 提问时间:12/11/2022 更新时间:12/11/2022 访问量:49
将字符串数组转换为浮点数组
Converting string array into float array
问:
我有多点看起来像这样:
points = '[1078.17,436.18],[1089.48,413.57],[1092.71,389.35],[1091.09,365.12],[1089.48,337.67],[1073.32,316.67],[1057.17,295.68],[1036.18,282.75],[1011.95,279.52],[987.73,273.06],[961.89,273.06],[937.66,276.29],[913.43,281.14],[894.05,297.29],[880.60,316.70],[874.20,343.10],[871.44,371.58],[868.21,395.81],[868.21,421.65],[887.59,437.80],[911.82,444.26],[936.04,449.11],[960.27,452.34],[984.50,453.95],[1010.34,457.18],[1034.56,455.57],[1058.79,447.49]'
点是字符串,但我正在尝试将其转换为浮点数,因此它看起来像这样:
points = [1078.17,436.18],[1089.48,413.57],[1092.71,389.35],[1091.09,365.12],[1089.48,337.67],[1073.32,316.67],[1057.17,295.68],[1036.18,282.75],[1011.95,279.52],[987.73,273.06],[961.89,273.06],[937.66,276.29],[913.43,281.14],[894.05,297.29],[880.60,316.70],[874.20,343.10],[871.44,371.58],[868.21,395.81],[868.21,421.65],[887.59,437.80],[911.82,444.26],[936.04,449.11],[960.27,452.34],[984.50,453.95],[1010.34,457.18],[1034.56,455.57],[1058.79,447.49]
艺术
points = [[1078.17,436.18],[1089.48,413.57],[1092.71,389.35],[1091.09,365.12],[1089.48,337.67],[1073.32,316.67],[1057.17,295.68],[1036.18,282.75],[1011.95,279.52],[987.73,273.06],[961.89,273.06],[937.66,276.29],[913.43,281.14],[894.05,297.29],[880.60,316.70],[874.20,343.10],[871.44,371.58],[868.21,395.81],[868.21,421.65],[887.59,437.80],[911.82,444.26],[936.04,449.11],[960.27,452.34],[984.50,453.95],[1010.34,457.18],[1034.56,455.57],[1058.79,447.49]]
在这种情况下,形状应为 27x2
我尝试了np.float和np.astype,但似乎不起作用。我用np.float得到的错误是:
<ipython-input-146-cdfdb0cec2ea>:1: DeprecationWarning: `np.float` is a deprecated alias for the builtin `float`. To silence this warning, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here.
Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations
np.float(test)
我也尝试了浮动本身:
float(points)
出现以下错误
ValueError: could not convert string to float: '[1078.17,436.18],[1089.48,413.57],[1092.71,389.35],[1091.09,365.12],[1089.48,337.67],[1073.32,316.67],[1057.17,295.68],[1036.18,282.75],[1011.95,279.52],[987.73,273.06],[961.89,273.06],[937.66,276.29],[913.43,281.14],[894.05,297.29],[880.60,316.70],[874.20,343.10],[871.44,371.58],[868.21,395.81],[868.21,421.65],[887.59,437.80],[911.82,444.26],[936.04,449.11],[960.27,452.34],[984.50,453.95],[1010.34,457.18],[1034.56,455.57],[1058.79,447.49]'
有人可以帮我将字符串转换为浮点数组吗?
答:
1赞
Teddy
12/11/2022
#1
如果积分字符串的输入不是来自用户,则可以使用:
result = eval(points)
这将返回浮点数列表的元组。
请注意,切勿将 eval 与用户输入一起使用。
2赞
Freese
12/11/2022
#2
试用模块ast
import ast
points = ast.literal_eval(points)
评论