【问题标题】:python read file into 2-dim array for looppython将文件读入2维数组for循环
【发布时间】:2018-09-23 00:37:09
【问题描述】:

如何读取二维数组中的文本文件,例如 将 numpy 导入为 np 将 matplotlib.pyplot 导入为 plt

fl = open('input.sis','r')

lines = [[]]
line=[]
for i in range(1000):
   for j in range(4):
      f= fl.readline()
      line[j].append(f)
      lines[i].append(line[j])

print(lines[0,1])

我正在尝试读取前 4 行并为它们分配 0-3 的索引,然后重复 1000 次。

我收到一个错误:

Traceback (most recent call last):
  File "./plot_inputsis.py", line 13, in <module>
    line[j].append(f)
IndexError: list index out of range

通过lines[i,j]访问数组元素对我来说很重要

【问题讨论】:

  • 能否添加小样本输入输出
  • @Tanmy jain 是的,这是 'input.sis' 的简短摘录:1.8303759014926360e-15 P000000 0 0 0 0 0 4.1404266989004412e+01 1.5577688734875311e+01 -4.4524452761790023e-01 -3.5777562203213698e-01 8.4611147063862890e-01 -2.9478803579751186e-02 1.3454764930562923e-15 P000001 0 0 0 0 0 -3.9537512656691270e+01 -1.6545256213770141e+01 -3.6618807991456764e-01 3.8908856145998982e-01 -8.6648838664890415e-01 7.8041511174565719e-03 1.2834912314620709e-15 P000002 0 0 0 0 0
  • 添加模拟值(一位或两位数)这看起来很笨拙,还请添加所需的输出。

标签: python arrays for-loop text-files


【解决方案1】:

考虑使用字典而不是列表。

lines = {}
for i in range(1000):
    for j in range(4):
    f=fl.readline()
    lines[j] = f
print(lines[0,1])

【讨论】:

    猜你喜欢
    • 2012-06-27
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多