Python-将字符串列表转换为浮点数-方括号和小数点导致问题 [英] Python - convert list of string to float - square braces and decimal point causing problems

查看:91
本文介绍了Python-将字符串列表转换为浮点数-方括号和小数点导致问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,其中包含一个较小的数据集(取自csv文件),像这样-

I have a text file that contains a smaller dataset(taken from csv file) like so -

2020-05-24T10:44:37.613168#[ 0.          0.         -0.06210425  0.        ]
2020-05-24T10:44:37.302214#[1. 1. 0. 0.]
2020-05-24T10:44:36.192222#[0. 0. 0. 0.]

然后使用

data = f.readlines()
for row in data:
    img_id, label = row.strip("\n").split("#")

其中label是一个类似于

where in label is a string list which looks like

[ 0.          0.         -0.24604772  0.        ]
[ 0.          0.         -0.24604772  0.        ]
[1. 1. 0. 0.]

我想将每个字符串元素转换为float.但是,方括号[]和十进制.阻止了我进行转换.

I'd like to convert each string element to float. However, the square brace [] and decimal . preventing me from converting.

到目前为止已尝试-

  1. []删除-label = label[1:-1],但是稍后我需要将它们作为数组. 然后,执行print([list(map(float, i.split())) for i in label])会导致错误ValueError: could not convert string to float: '.'

  1. Removing [] so - label = label[1:-1] but I would need them as an array later. Then doing this print([list(map(float, i.split())) for i in label]) resulted in error ValueError: could not convert string to float: '.'

使用ast.literal_eval.label = ast.literal_eval(row.strip("\n").split("#")).获取ValueError: malformed node or string: ['2020-05-24T10:57:52.882241 [0. 0. 0. 0.]']

已推荐

需要将字符串读入float数组

无法转换列表使用float()将字符串转换为python中的float列表

如何使用Python将字符串列表转换为浮点列表?

将字符串列表转换为numpy浮点数数组

何时使用ast.literal_eval

所以

  1. 我还应该尝试什么才能将它们转换为可迭代的float数组?还是我做错了什么?我必须删除方括号吗?
  2. 如果我可以使事情变得容易得多,如何将数据存储在txt文件中?在这种情况下,CSV比txt更好吗?
  3. 我需要将此逻辑扩展到110,000个条目.那么任何步骤都会引起问题吗?

谢谢.任何帮助将不胜感激.请帮忙.

Thank you. Any help will be greatly appreciated. Please help.

推荐答案

对于每行,用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]

这篇关于Python-将字符串列表转换为浮点数-方括号和小数点导致问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆