gpt4 book ai didi

Python - 删除现在小于其后面数字的所有数字

转载 作者:太空宇宙 更新时间:2023-11-04 08:47:30 25 4
gpt4 key购买 nike

我在我的函数文件中为此创建了一个函数:

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]

关于Python - 删除现在小于其后面数字的所有数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38879119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com