【发布时间】:2020-04-09 09:20:43
【问题描述】:
我有一个代表一个巨大矩阵的文件:
54321
| This | Table | |
|:------: |:-----: |:-----: |
| 6.75 | 0 | 20020 |
| 1 | 0 | 13663 |
| 107.75 | 0 | 0 |
| 0.25 | 1 | 27508 |
| 5.5 | 1 | 10964 |
| 11 | 1 | 19826 |
| 9 | 1 | 19817 |
| 7.75 | 1 | 27525 |
| 1.75 | 1 | 13005 |
| 5.25 | 1 | 2441 |
| 1.75 | 1 | 17250 |
| 142.25 | 1 | 1 |
其中第一行是维度,第二行是一个元组,看起来像(来自稀疏矩阵的元素、行索引、列索引)。
我必须从这个文件中读取维度并生成矩阵存储的向量。
def getLineIndex(a, x):
for lineIndex in range(0, len(a)):
diagonalValue, lineNumber = a[lineIndex][-1]
if lineNumber == x:
return lineIndex
return -1
def getColumnIndex(a, x, y):
line = a[x]
for i in range(0, len(line)):
value, columnNumber = line[i]
if columnNumber == y:
return i
return -1
def read_values(filename):
with open(filename,'r') as file:
n = int(file.readline())
b = list()
for i in range(0, n):
b.append((file.readline()))
a = list()
for line in file:
values = line.replace(",", " ").split()
value = Decimal(values[0])
x = int(values[1])
y = int(values[2])
lineIndex = getLineIndex(a, x)
if lineIndex != -1:
columnIndex = getColumnIndex(a, lineIndex, y)
if columnIndex != -1:
a[lineIndex][columnIndex][0] += value
else:
# #addNewColumn(a, value, lineIndex, y)
a[lineIndex].insert(0, [value, y])
但我收到此错误:
文件“source.py”,第 31 行,在 read_values 中 值 = 十进制(值 [0]) IndexError: 列表索引超出范围
感谢任何类型的帮助。
【问题讨论】:
-
该命令执行前的值是什么状态?你能打印出来吗?
-
该错误消息意味着
values是一个空列表。这很可能意味着line也是空的。
标签: python python-3.x list decimal