【问题标题】:Python "List assignment index out of range"Python“列表分配索引超出范围”
【发布时间】:2015-11-06 03:18:28
【问题描述】:

我是 Python(以及一般编程)的新手。

我应该制作一个 python 程序,它打开两个带有随机数的文件,并创建一个新文件,其中的数字从低到高排列。

所以我编写了这段代码,使用两个 for 循环遍历所有数字,搜索最低的、非常基本的东西,然后存储数字及其位置,附加到将保存在最终文件中的 Lmix 列表中存储数字位置以将其从该列表中删除,因此不会再次被发现。

变量是葡萄牙语,但我在 cmets 中翻译了它们,其余的不言自明。

arq1 = open("nums1.txt","r")
arq2 = open("nums2.txt","r")

arqmix = open("numsord.txt","w")

L1 = arq1.readlines()
L2 = arq2.readlines()
Lmix = []

L1 = list(map(int,L1)) # converts lists into int
L2 = list(map(int,L2))

cont = 0

menor = L1[0]  # "Menor" is the variable that stores the lowest number it finds
menorpos = 0   # "Menorpos" is the position of that variable in the list, so it can delete later
listdec = 0    # "listdec" just stores which list the number was from to delete.

while cont != (len(L1)+len(L2)):   

# while loops that finds the lowest number, stores the number and position, appends to the Lmix and deletes from the list so it won't be found on next   iteration

    n = 0
    for n,x in enumarate(L1):
        m = 0
        for m,y in enumarate(L2):
            if x<menor:
                menor = x
                menorpos = n
                listdec = 0
            elif y<menor:
                menor = y
                menorpos = m
                listdec = 1
            m += 1
        n += 1

    Lmix.append(menor)
    if listdec == 0:
        del L1[menorpos]
    elif listdec == 1:
        del L2[menorpos]
    cont += 1

for x in Lmix:
    arqmix.write("%d\n"%x)

arq1.close()
arq2.close()
arqmix.close()

但是每次运行都会出现这个错误:

Traceback(最近一次调用最后一次): 文件“C:/Users/Danzmann-Notebook/PycharmProjects/untitled/aula18.py”,第 41 行,在 del L2[menorpos] IndexError: 列表赋值索引超出范围

我知道这意味着什么,但我就是不明白为什么会发生,我该如何解决。

任何帮助将不胜感激。

提前致谢,如有语法错误,请见谅,英语不是我的母语。

【问题讨论】:

  • 为什么要在 for 循环中显式递增 mn?这已经为您完成了。

标签: python list file indexing numbers


【解决方案1】:

为了调试它,我在 while 循环中添加了两个打印语句 - 这是我看到的:

Cont: 0  L1 [9, 2, 6, 4, 7]  L2 [3, 15, 5, 8, 12]  Lmix []
  Found menor 2 menorpos 1 listdec 0

Cont: 1  L1 [9, 6, 4, 7]  L2 [3, 15, 5, 8, 12]  Lmix [2]
  Found menor 2 menorpos 1 listdec 0

Cont: 2  L1 [9, 4, 7]  L2 [3, 15, 5, 8, 12]  Lmix [2, 2]
  Found menor 2 menorpos 1 listdec 0

Cont: 3  L1 [9, 7]  L2 [3, 15, 5, 8, 12]  Lmix [2, 2, 2]
  Found menor 2 menorpos 1 listdec 0

Cont: 4  L1 [9]  L2 [3, 15, 5, 8, 12]  Lmix [2, 2, 2, 2]
  Found menor 2 menorpos 1 listdec 0

Traceback (most recent call last):
  File "<pyshell#30>", line 29, in <module>
    del L1[menorpos]
IndexError: list assignment index out of range

第一次循环时,它可以正常工作 - 它在任一列表中找到最低的项目,将正确的值分配给 menor、menorpos 和 listdec,然后删除该值。

第二次循环失败,因为 menor 已经是最低值 - 它没有找到更低的值,因此它永远不会更新 menor、menorpos 和 listdec 的值。它使用以前的值(现在不正确)。

它会重复使用错误的值,直到要删除的列表太短;然后它会抛出一个错误。


这个问题可以更简单地解决:

def loadnums(filename):
    with open(filename) as inf:
        nums = [int(line) for line in inf]
    return nums

nums = loadnums("num1.txt") + loadnums("num2.txt")
nums.sort()

with open("numsord.txt", "w") as outf:
    outf.write("\n".join(str(num) for num in nums))

【讨论】:

    【解决方案2】:

    您不需要显式增加 m 和 n。这已经为你完成了。这可能导致索引超出范围。

        m += 1
    n += 1
    

    【讨论】:

      猜你喜欢
      • 2013-05-31
      • 2018-10-21
      • 2019-06-18
      • 2020-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-19
      • 1970-01-01
      相关资源
      最近更新 更多