我试图调试这个,我不知道如何使它工作
def makeUnique(numList):
"""Takes in a list of numbers, sorts them, and then removes duplicate numbers, modifying the input list."""
numList.sort() # making sure that numList is taken as a list.
i = 0
while i < (len(numList)):
if numList == numList[i+1]: #I'm sure this is where the problem is.
del numList[i+1]
else:
i = i + 1
你实际上有两个问题,但第一个问题在哪里你是对的。这条线:
…正在测试
numList
的整个是否等于它的第i+1
个元素,这显然是不正确的。应该是这样的:…它测试第
i
个元素是否等于第i+1
个元素第二个问题是,上次在
for
循环中,列表中有i+1
个元素,但是if
语句中的numList[i+1]
试图在最后一个之后找到一个元素(因为Python的zero-based indexing),然后出现了一个错误:如果更换管路:
与
…您将少循环一次,避免从列表末尾掉下来
解决这两个问题后,您将得到以下结果:
…按预期工作:
相关问题 更多 >
编程相关推荐