我在我的函数文件中为此创建了一个函数:
def removeNum(myList):
listSize = len(myList) -1
loop = 0
while loop < listSize:
if myList[loop] > myList[loop + 1]:
myList.remove(myList[loop + 1])
listSize = listSize - 1
loop = loop + 1
return myList
我的主程序看起来像:(我使用 removeNum 函数,我在代码底部遇到了问题。)
import functionsFile
finalDataList = []
openFinalData = open("FinalData.data")
for entry in openFinalData:
entry = entry.strip()
entry = int(entry)
finalDataList.append(entry)
print("The file has been read")
listSum = 0
for numb in finalDataList:
listSum = listSum + numb
listAvg = listSum / len(finalDataList)
listAvg = round(listAvg,2)
print("The sum of all the numbers:--> "+str(listSum))
print("The average of the numbers is:--> "+str(listAvg))
functionsFile.firstTen(finalDataList)
functionsFile.lastTen(finalDataList)
finalDataList.sort()
finalDataList.reverse()
print("After sorting the numbers")
functionsFile.firstTen(finalDataList)
functionsFile.lastTen(finalDataList)
oddNumList = []
for numb in finalDataList:
oddNumList.append(functionsFile.makeOdd(numb))
finalDataList = oddNumList
newListSum = 0
for numb in finalDataList:
newListSum = newListSum + numb
newListAvg = newListSum / len(finalDataList)
newlistAvg = round(newListAvg,2)
print("After replacing the list with all the answers,"
+"here are the new totals")
print(" The new sum of all the numbers will be: "+str(newListSum))
print("The new average of all the numbers will be:"+str(newListAvg))
print(" ")
functionsFile.firstTen(finalDataList)
functionsFile.lastTen(finalDataList)
print(" ")
print(" ")
functionsFile.removeNum(finalDataList)
print(finalDataList)
openFinalData.close()
当我运行程序时,它没有打印出从上面的 removeNum 函数修改后的新列表,是我的函数有问题还是我的主程序有问题?我没有收到任何错误。任何想法将不胜感激。谢谢。
请您参考如下方法:
解决该问题的一种方法是zip 将列表自身的副本偏移 1,然后使用列表推导式进行过滤,如下所示:
ls = [1, 3, 0, 7, 9, 4]
zipped = zip(ls, ls[0:1] + ls[:-1])
ls_filtered = [p[0] for p in zipped if p[0] >= p[1]]
# ls_filtered is now [1, 3, 7, 9]
