Python“列表分配索引超出范围”

2024-09-30 03:24:17 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我应该做一个python程序,打开两个随机数的文件,然后创建一个新文件,其中的数字从最低到最高排序。在

所以我做了这个代码,用两个for循环遍历所有的数字,搜索最低的,非常基本的东西,然后存储数字和它的位置,附加到一个Lmix列表中,这个列表将保存在最后的文件中,并存储数字的位置,将其从列表中删除,这样就不会再找到它了。在

变量是葡萄牙语,但我在评论中翻译了它们,其余的都是不言而喻的。在

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()

但每次我运行它时,都会出现以下错误:

回溯(最近一次呼叫): 文件“C:/Users/Danzmann Notebook/PycharmProjects/untitled/aula18.py”,第41行,英寸 L2级[美诺波斯] 索引器错误:列表分配索引超出范围

我知道这意味着什么,但我就是不明白为什么会这样,我该怎么解决它。在

任何帮助都将不胜感激。在

提前谢谢,很抱歉有语法错误,英语不是我的母语。在


Tags: 文件theinl1number列表for数字
2条回答

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

    m += 1
n += 1

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

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的值。它使用以前的值(现在不正确)。在

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


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

^{pr2}$

相关问题 更多 >

    热门问题