[英]What is the problem in the below code for "removing duplicates in list". I know we can use append() to do the same thing
What is the problem in the below code for "removing duplicates in ~~~list".以下代码中“删除 ~~~list 中的重复项”的问题是什么? I know we can use append() to do the same thing.
我知道我们可以使用 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/
If you use the following castings your list won't contain duplication and it will be sorted.如果您使用以下转换,您的列表将不包含重复,并且将被排序。
numbers = sorted(list(set(numbers)))
EDIT:编辑:
Complete implementation:完整实施:
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)
Output: Output:
>>> python test.py
[2, 3, 4, 5, 6, 7, 9, 11, 81, 101]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.