首页 > 解决方案 > python从文本文件到数组传输

问题描述

我有一个文本文件,如下所示:

[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.

所有元素都是浮动的。

我该怎么做?谢谢。

标签: pythonarrayslistnumpy

解决方案


这是一种方法

#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)

推荐阅读