【发布时间】:2018-12-19 15:17:10
【问题描述】:
我正在尝试将文本文件中的数据读取到二维数组中,然后访问数据的每个元素。我尝试了许多不同的方法,但我无法访问数据的每个元素,
这是数据的摘录,
GRID 16 7.5 5.961539 0.
GRID 17 7.5 11.92308 0.
GRID 18 7.5 17.88461 0.
GRID 19 7.5 23.84615 0.
GRID 20 7.5 29.80769 0.
GRID 21 7.5 35.76923 0.
GRID 22 7.5 41.73077 0.
GRID 23 7.5 47.69231 0.
GRID 24 7.5 53.65384 0.
使用此处的示例,Import nastran nodes deck in Python using numpy
它可以导入,但它是一个一维数组,例如,我得到以下响应,
x[1,1]
Traceback (most recent call last):
File "<ipython-input-85-3e593ebbc211>", line 1, in <module>
x[1,1]
IndexError: too many indices for array
我希望的是,
17
我也试过下面的代码,它再次读入一维数组,
ary = []
with open(os.path.join(dir, fn)) as fi:
for line in fi:
if line.startswith('GRID'):
ary.append([line[i:i+8] for i in range(0, len(line), 8)])
我收到以下错误,
ary[1,2]
Traceback (most recent call last):
File "<ipython-input-83-9ac21a0619e9>", line 1, in <module>
ary[1,2]
TypeError: list indices must be integers or slices, not tuple
我是 Python 新手,但我确实有使用 VBA 的经验,我在其中经常使用数组,但我很难理解如何加载数组以及如何访问特定数据。
【问题讨论】:
-
检查
shape和dtype。不要假设文本是如何加载的。
标签: python python-3.x numpy multidimensional-array