Arrays Python 2.7将2d字符串数组转换为浮点数组
我在.txt文件中读取以下字符串 {1,2,3,0},{4,5,6,7},{8,-1,9,0} 使用Arrays Python 2.7将2d字符串数组转换为浮点数组,arrays,python-2.7,Arrays,Python 2.7,我在.txt文件中读取以下字符串 {1,2,3,0},{4,5,6,7},{8,-1,9,0} 使用lin=lin.strip()删除'\n' 然后我使用 lin = lin.replace ("{", "[") lin = lin.replace ("}", "]") 我的目标是将lin转换为浮点2d数组。所以我做了 my_matrix = np.array(lin, dtype=float) 但我收到一条错误消息:“ValueError:无法将字符串转换为浮点:[[1,2,3,0],[
lin=lin.strip()
删除'\n'
然后我使用
lin = lin.replace ("{", "[")
lin = lin.replace ("}", "]")
我的目标是将lin转换为浮点2d数组。所以我做了
my_matrix = np.array(lin, dtype=float)
但我收到一条错误消息:“ValueError:无法将字符串转换为浮点:[[1,2,3,0],[1,1,1,2],[0,-1,3,9]。”
删除数据类型后,我得到一个字符串数组。我已经尝试将lin乘以1.0,使用.astype(float)复制lin,但似乎没有任何效果。我正在使用
JSON
库解析文件内容,然后遍历数组并将每个元素转换为float。但是,整数解决方案可能已经足够满足您的需要。那个更快更短
import json
fc = '{{1,2,3,0},{4,5,6,7},{8,-1,9,0}}'
a = json.loads(fc.replace('{','[').replace('}',']'))
print(a) # a is now array of integers. this might be enough
for linenumber, linecontent in enumerate(a):
for elementnumber, element in enumerate(linecontent):
a[linenumber][elementnumber] = float(element)
print(a) # a is now array of floats
短解
import json
fc = '{{1,2,3,0},{4,5,6,7},{8,-1,9,0}}'
a = json.loads(fc.replace('{','[').replace('}',']'))
print(a) # a is now array of integers. this might be enough
a = [[float(c) for c in b] for b in a]
print(a) # a is now array of floats
(适用于python 2和python 3)
虽然这可能不是最优雅的解决方案,但我认为它很容易遵循,并提供了您想要的东西。您希望使用哪种类型的浮动?是否要获取浮点数组
[[1.0,2.0,3.0,0.0],[4.0,5.0,6.0,7.0],[8.0,-1.0,9.0,0.0]]
或某种连接1230.4567
?可能您最好的选择是使用JSON库:导入JSON;loads(filecontent)
这将为您提供一个整数数组,您可以进行计算with@kamik423我想要一个浮动数组[[1.0,2.0,3.0,0.0],[4.0,5.0,6.0,7.0],[8.0,-1.0,9.0,0.0]]这救了我一天!
import numpy as np
readStr = "{{1,2,3,0},{4,5,6,7},{8,-1,9,0}}"
readStr = readStr[2:-2]
# Originally read string is now -> "1,2,3,0},{4,5,6,7},{8,-1,9,0"
line = readStr.split("},{")
# line is now a list object -> ["1,2,3,0", "4,5,6,7", "8,-1,9,0"]
array = []
temp = []
# Now we iterate through 'line', convert each element into a list, and
# then append said list to 'array' on each iteration of 'line'
for string in line:
num_array = string.split(',')
for num in num_array:
temp.append(num)
array.append(temp)
temp = []
# Now with 'array' -> [[1,2,3,0], [4,5,6,7], [8,-1,9,0]]
my_matrix = np.array(array, dtype = float)
# my_matrix = [[1.0, 2.0, 3.0, 0.0]
# [4.0, 5.0, 6.0, 7.0]
# [8.0, -1.0, 9.0, 0.0]]