下面的代码中有什么问题"removing duplicates in list".我知道我们可以使用 append() 做同样的事情



"删除~~~列表中的重复项"的代码中有什么问题。我知道我们可以使用append((做同样的事情。

    l=0
    numbers = [101,3,7,2,3,5,9,11,11,11,9,4,9,81,6]
    numbers.sort()
    for each_element in numbers:
        if each_element==l:
            l = each_element
            numbers.remove(each_element) 
        else:
            l=each_element
    print(numbers)  
~~~ end of code
As pointed by *Gino Mempin* It is not a good idea to modify the list while iterating through it.
Your code logic is correct but that's not how things are happening here.
Understand by this,
let list is [2, 3, 3, 4, 5, 6, 7, 9, 9, 9, 11, 11, 11, 81, 101],
Now when for loop iterates and detects a duplicate at index 2 then '3' at index 2 is removed.
It's what you wanted it to do but problem is that now '4' comes at index 2 from where '3' is removed. But python for loop has already iterated index 2 which means it don't care about whether there has come a new value and it simply iterate from index 3 now knowingly that the list has been modified.
Because of this it's giving you wrong output from your expectation but in actual it's not a python error but in logic according with python/

如果您使用以下铸件,则列表将不包含重复,并且会进行排序。

numbers = sorted(list(set(numbers)))

编辑:

完成实施:

numbers = [101, 3, 7, 2, 3, 5, 9, 11, 11, 11, 9, 4, 9, 81, 6]
sorted_numbers = sorted(list(set(numbers)))
print(sorted_numbers)

输出:

>>> python test.py 
[2, 3, 4, 5, 6, 7, 9, 11, 81, 101]

相关内容

最新更新