为什么我的uniquesort函数会提升索引器?

2024-06-14 19:22:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图调试这个,我不知道如何使它工作

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

Tags: andoftheinisdeflistnumbers
1条回答
网友
1楼 · 发布于 2024-06-14 19:22:45

你实际上有两个问题,但第一个问题在哪里你是对的。这条线:

        if numList == numList[i+1]:

…正在测试numList的整个是否等于它的第i+1个元素,这显然是不正确的。应该是这样的:

        if numList[i] == numList[i+1]:

…它测试第i个元素是否等于第i+1个元素

第二个问题是,上次在for循环中,列表中有i+1个元素,但是if语句中的numList[i+1]试图在最后一个之后找到一个元素(因为Python的zero-based indexing),然后出现了一个错误:

IndexError: list index out of range

如果更换管路:

    while i < (len(numList)):

    while i < (len(numList) - 1):

…您将少循环一次,避免从列表末尾掉下来

解决这两个问题后,您将得到以下结果:

def makeUnique(numList):        
    numList.sort()
    i = 0
    while i < (len(numList) - 1):
        if numList[i] == numList[i+1]:
            del numList[i+1]
        else:
            i = i + 1

…按预期工作:

>>> s = [82, 101, 112, 101, 116, 105, 116, 105, 111, 117, 115]
>>> makeUnique(s)
>>> s
[82, 101, 105, 111, 112, 115, 116, 117]

相关问题 更多 >