不,问题是你的第一行以逗号结尾:
5.0, 1000.0, 100000000000000.0, 115.2712, 230.538, 345.796, 461.0408,
1.053E-09, 1.839E-09, 1.632E-10, 1.959E-12, 4.109, 3.683, 3.586, 3.650
因此,您想要处理一个字符串仅包含空格 (like ' '
). And float(' ')
失败,因为它不是一个数字(它实际上报告了这一点):
>>> float(' ')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float:
>>> float('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'a'
但打印时空格是不可见的。
您可以通过添加一个来解决它过滤语句列表理解:
T = []
with open("test.txt", "r") as file1:
for line in file1.readlines():
f_list = [float(i) for i in line.split(",") if i.strip()]
T += f_list[7:11]
此外,这将not工作以来没有一行有 7-11漂浮。所以无论如何你都不会添加这些浮动。
但是您可以使用以下代码:
with open("test.txt", "r") as file1:
f_list = [float(i) for line in file1 for i in line.split(',') if i.strip()]
T = f_list[7:11]
这将导致T
等于:
>>> T
[1.053e-09, 1.839e-09, 1.632e-10, 1.959e-12]