Python“列表分配索引超出范围”
我是Python和编程方面的新手 我应该制作一个python程序,打开两个文件,其中包含随机数,并创建一个新文件,其中的数字从最低到最高排列 因此,我编写了这段代码,它使用两个for循环遍历所有数字,搜索最低的、非常基本的内容,然后存储数字及其位置,附加到一个Lmix列表,该列表将保存在最终文件中,并存储数字位置以从该列表中删除它,这样就不会再次找到它 变量是葡萄牙语的,但我在评论中翻译了它们,其余的都是不言自明的Python“列表分配索引超出范围”,python,list,file,indexing,numbers,Python,List,File,Indexing,Numbers,我是Python和编程方面的新手 我应该制作一个python程序,打开两个文件,其中包含随机数,并创建一个新文件,其中的数字从最低到最高排列 因此,我编写了这段代码,它使用两个for循环遍历所有数字,搜索最低的、非常基本的内容,然后存储数字及其位置,附加到一个Lmix列表,该列表将保存在最终文件中,并存储数字位置以从该列表中删除它,这样就不会再次找到它 变量是葡萄牙语的,但我在评论中翻译了它们,其余的都是不言自明的 arq1 = open("nums1.txt","r") arq2 = open
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/pycharm项目/untitled/aula18.py,第41行,in
del L2[menorpos]
索引器:列表分配索引超出范围
我知道这意味着什么,但我就是不明白为什么会发生,我怎么才能解决它
任何帮助都将不胜感激
提前感谢,抱歉出现语法错误,英语不是我的母语。为了调试这一点,我在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
您不需要显式地增加m和n。这已经为你做了。这可能会导致索引超出范围
m += 1
n += 1
为什么在for循环中显式增加m和n?这已经为你做了。
m += 1
n += 1