以下代码中的“删除列表中的重复项”有什么问题?我知道我们可以使用append()做同样的事情

时间:2019-05-20 04:35:03

标签: python-3.x

以下代码中的“删除~~~列表中的重复项”有什么问题?我知道我们可以使用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

2 个答案:

答案 0 :(得分:0)

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/

答案 1 :(得分:0)

如果您使用以下强制类型转换,您的列表将不包含重复项,并且将对其进行排序。

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]