【发布时间】:2021-07-30 11:51:07
【问题描述】:
我有一个像这样的文本文件:
[0.001,0.02,0.003]
[0.004,0.05,0.006]
我想创建一个这样的数组:
array([0.001,0.02,0.003],
[0.004,0.05,0.006]) etc.
所有元素都是浮动的。
我该怎么做?谢谢。
【问题讨论】:
我有一个像这样的文本文件:
[0.001,0.02,0.003]
[0.004,0.05,0.006]
我想创建一个这样的数组:
array([0.001,0.02,0.003],
[0.004,0.05,0.006]) etc.
所有元素都是浮动的。
我该怎么做?谢谢。
【问题讨论】:
这是一种方法
#First open the text file and turn each line into an element of a list.
with open("file.txt", 'r') as file_handle:
# convert file contents into a list
lines = file_handle.read().splitlines()
#Then convert the string into a list
for i in range(len(lines)):
#remove the "[" and "]" and split where there is a ","
lines[i] = lines[i].strip("[]").split(",")
for j in range(len(lines[i])):
#convert string to float
lines[i][j] = float(lines[i][j])
print(lines)
【讨论】: