首页 > 解决方案 > How to save floats from txt file with multiple arrays?

问题描述

I would like to extract data from a txt file stored as:

[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]

(there is no vertical space between the brackets though)

Would you have any idea how to proceed? I have tried this below which does not recognize the brackets.

with open(filename) as f:
    array = []
    for line in f:
        array.append([float(x) for x in line.split()])

标签: pythonlist

解决方案


假设括号中的每个子列表都存储在新行上。

替换line.split()为:

line.strip()[1:-1].split()

这只是用 . 去掉了两个括号(或第一个和最后一个字符)[1:-1]


推荐阅读