【问题标题】:python from textfile to array transferpython从文本文件到数组传输
【发布时间】: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.

所有元素都是浮动的。

我该怎么做?谢谢。

【问题讨论】:

    标签: python arrays list numpy


    【解决方案1】:

    这是一种方法

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-01
      • 2018-06-20
      • 2023-04-05
      • 1970-01-01
      相关资源
      最近更新 更多