【问题标题】:Decimal list index out of range十进制列表索引超出范围
【发布时间】: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


【解决方案1】:

在您的第一行,即54321,没有空格或“,”。所以用空格或“,”分割返回无。因此值数组为空。当您尝试访问values[0] 时,会出现此错误:IndexError: list index out of range。 这应该有效:

for line in file:
    values = line.replace(",", " ").split()  //line number 30
    if len(values) == 0:
       continue
    value = Decimal(values[0])

【讨论】:

  • @Biax 您可能希望确保在该 for 循环中正在读取任何内容。您已经遍历了整个文件,因此您在文件中的位置位于底部
  • 这是跳过第一行的一个很好的解决方案,但您可能还需要回到文件的开头
【解决方案2】:

我认为您的line 变量为空,导致values 为空,因为您已经遍历了所有行并将它们放入b,所以现在您尝试从底部读取文件,它可能正在读取空行。您可能希望在使用类似这样的内容再次遍历每一行之前返回文件的开头:file.seek(0, os)。回到文件顶部后,您可以使用@NanduRaj 的解决方案跳过第一行并根据需要进行迭代。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 2011-06-14
    • 2016-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多