我有一个简单的字符串数据集,我想将其转换为浮点数。出于某种原因,以下工作:
dataset = open("data1.5.txt", "r")
array = dataset.read().split(", \n")
array2 = [float(array[0])]
print(array2)
但如果我这样做:
dataset = open("data1.5.txt", "r")
array = dataset.read().split(", \n")
array2 = [float(i) for i in array]
print(array2)
我收到以下错误:
ValueError Traceback (most recent call last)
<ipython-input-158-d3f4342981c6> in <module>()
1 dataset = open("data1.5.txt", "r")
2 array = dataset.read().split(", \n")
----> 3 array2 = [float(i) for i in array]
4 print(array2)
<ipython-input-158-d3f4342981c6> in <listcomp>(.0)
1 dataset = open("data1.5.txt", "r")
2 array = dataset.read().split(", \n")
----> 3 array2 = [float(i) for i in array]
4 print(array2)
ValueError: could not convert string to float:
如果我尝试:
dataset = open("data1.5.txt", "r")
array = dataset.read().split(", \n")
array2 = [float(array[i]) for i in array]
print(array2)
我收到以下错误:
TypeError Traceback (most recent call last)
<ipython-input-160-60a5ed9c866f> in <module>()
1 dataset = open("data1.5.txt", "r")
2 array = dataset.read().split(", \n")
----> 3 array2 = [float(array[i]) for i in array]
4 print(array2)
<ipython-input-160-60a5ed9c866f> in <listcomp>(.0)
1 dataset = open("data1.5.txt", "r")
2 array = dataset.read().split(", \n")
----> 3 array2 = [float(array[i]) for i in array]
4 print(array2)
TypeError: list indices must be integers or slices, not str
最后,如果我尝试浏览map(),我可以创建:
dataset = open("data1.5.txt", "r")
array = dataset.read().split(", \n")
array2 = map(float, array)
print(array2)
但是只返回Python 3中的一个位置;如果我试着将它变成这样的列表:
dataset = open("data1.5.txt", "r")
array = dataset.read().split(", \n")
array2 = list(map(float, array))
print(array2)
我再次收到错误:
ValueError Traceback (most recent call last)
<ipython-input-164-68394d0c25fd> in <module>()
1 dataset = open("data1.5.txt", "r")
2 array = dataset.read().split(", \n")
----> 3 array2 = list(map(float, array))
4 print(array2)
ValueError: could not convert string to float:
我还尝试将值附加到for循环中的新列表但无济于事。我对Python很新,这是坦率的混淆......为什么float()似乎适用于我的数据的一次迭代而不适用于整个集合?
请注意,float()方法适用于数组的任何一点,打印数组给我一个&#34; clean&#34;字符串列表,这里有一段摘录:
['0.60237078', '0.404667', '0.081656125', '0.99716862', '0.70149429', '0.59545983', '0.97768306', '0.86360343', '0.57052565', '0.47777524', '0.040106169', ...]
答案 0 :(得分:0)
尝试添加一些错误处理代码:
SIGSEGV
有可能在初始字符串数组中的某处隐藏了一个或多个非浮点值,这些值会使事情变得混乱,但是因为你有很多值,所以你在某处遗漏了一个值。