【发布时间】: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 循环中显式递增
m和n?这已经为您完成了。
标签: python list file indexing numbers