python - 在python中将数据文件读取到多维数组中

标签 python arrays multidimensional-array

我是Python新手。我想从文件中读取数据并将其存储在多维数组中。例如,我有这个,

6 5.9
6.3 5.9
6.6 6.3

7.8 7.5
7.8 7.3
7.5 7.6

8.3 8
8.5 8
8.2 8.3

9.2 8.5
9 8.5
9.2 8.9

我希望将其存储在这样的数组中:

[ [['6', '5.9'], ['6.3', '5.9'], ['6.6', '6.3']], 
  [['7.8', '7.5'], ['7.8', '7.3'], ['7.5', '7.6']], 
      [['8.3', '8'], ['8.5', '8'], ['8.2', '8.3']], 
      [['9.2', '8.5'], ['9', '8.5'], ['9.2', '8.9']] ]

到目前为止我已经尝试过:

with open("number.txt") as textFile:
    lines = [line.split() for line in textFile]
print(lines)

它给了我这样的:

[['6', '5.9'], ['6.3', '5.9'], ['6.6', '6.3'], [], ['7.8', '7.5'], ['7.8', '7.3'], ['7.5', '7.6'], [], ['8.3', '8'], ['8.5', '8'], ['8.2', '8.3'], [], ['9.2', '8.5'], ['9', '8.5'], ['9.2', '8.9']]

最佳答案

以下代码将为您提供所需的结果:

import re

dim3 = []
dim2 = []
f = open ('inputfile.txt', 'r')
for s in f.readlines():
    s = s.strip()
    if s == '':
        dim3.append(dim2)
        dim2 = []
    else:
        dim1 = re.split('\s+', s)
        dim2.append(dim1)
if len(dim2) > 0:
    dim3.append(dim2)
f.close()

print(dim3)

它基本上维护 dim2/3 维度变量来保存值,以及 dim1 维度变量来处理每行。

对于每个非空行,我们计算数组 dim1 并将其添加到当前的 dim2 中。如果找到空行,我们会将当前的 dim2 添加到 dim3 并重置 dim2

最后,我们处理任何剩余的 dim2 ,生成的 dim3 就是您想要的多维数组(为了便于阅读而格式化):

[[['6'  , '5.9'], ['6.3', '5.9'], ['6.6', '6.3']],
 [['7.8', '7.5'], ['7.8', '7.3'], ['7.5', '7.6']],
 [['8.3', '8'  ], ['8.5', '8'  ], ['8.2', '8.3']],
 [['9.2', '8.5'], ['9'  , '8.5'], ['9.2', '8.9']]]

该代码可以处理任意尺寸,从某种意义上说,它允许任意数量的每行数字、每组行数和每文件组数。

关于python - 在python中将数据文件读取到多维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33557717/

相关文章:

python - 从嵌套列表创建字典的有效方法

jquery - 如何在 jQuery 中解析 JSON 数组?

javascript - 将等级作为对象值从最高到最低排序

c++ - 如何使用 new 在 C++ 中声明二维数组?

Python:set.pop() 的用例是什么?

python - 在括号之间插入乘号

Python 长列表目录 (ls -l), ls *

java - 我如何计算我的代码的平均值

c# - System.Type.FullName 的意外值

php - 从多维数组中获取特定值